竞博体育 > 应用 > 【竞博体育app下载】//所在点的相对角度,当canvas的鼠标click事件触发后

【竞博体育app下载】//所在点的相对角度,当canvas的鼠标click事件触发后

html5版canvas自由拼图实例,html5canvas拼图

这篇文章主要为大家介绍了html5版canvas自由拼图实例,较为详细的讲述了该功能的完整实现过程,具有一定的参考学习价值,需要的朋友可以参考下

本文实例讲述了html5版canvas自由拼图的实现方法。分享给大家供大家参考。具体方法如下:

代码运行效果如下图所示:

竞博体育app下载 1 

canvasElement.js代码如下:

代码如下:

define('canvasElement', [ '../multi_upload/core' ], function(S) {
var Canvas = window.Canvas || {};
(function () {
Canvas.Element = function() {};
Canvas.Element.prototype.fillBackground = true;
Canvas.Element.prototype.showcorners = false;
Canvas.Element.prototype.photoborder = true;
Canvas.Element.prototype.polaroid = false;
Canvas.Element.prototype._backgroundImg = null;
Canvas.Element.prototype._groupSelector = null;
Canvas.Element.prototype._aImages = null;
Canvas.Element.prototype._oContext = null;
Canvas.Element.prototype._oElement = null;
Canvas.Element.prototype._oConfig = null;
Canvas.Element.prototype._currentTransform = null;
Canvas.Element.prototype._prevTransform = null;
Canvas.Element.prototype.curAngle = null;
Canvas.Element.prototype.init = function(el, oConfig) {
if (el == '') {
return;
}
this._initElement(el);
this._initConfig(oConfig);
this._createCanvasBackground();
this._createContainer();
this._initEvents();
this._initCustomEvents();
};
Canvas.Element.prototype._initElement = function(el) {
this._oElement = document.getElementById(el);
this._oContextTop = this._oElement.getContext('2d');
};
Canvas.Element.prototype._initCustomEvents = function() {
this.onRotateStart = new Canvas.CustomEvent('onRotateStart');
this.onRotateMove = new Canvas.CustomEvent('onRotateMove');
this.onRotateComplete = new Canvas.CustomEvent('onRotateComplete');
this.onDragStart = new Canvas.CustomEvent('onDragStart');
this.onDragMove = new Canvas.CustomEvent('onDragMove');
this.onDragComplete = new Canvas.CustomEvent('onDragComplete');
};
Canvas.Element.prototype._initConfig = function(oConfig) {
this._oConfig = oConfig;
this._oElement.width = this._oConfig.width;
this._oElement.height = this._oConfig.height;
this._oElement.style.width = this._oConfig.width + 'px';
this._oElement.style.height = this._oConfig.height + 'px';
};
Canvas.Element.prototype._initEvents = function() {
var _this=this;
S(this._oElement).on('mousedown',function(e){
_this.onMouseDown(e);
});
S(this._oElement).on( 'mouseup', function(e){
_this.onMouseUp(e);
});
S(this._oElement).on('mousemove', function(e){
_this.onMouseMove(e);
});
};
Canvas.Element.prototype._createContainer = function() {
var canvasEl = document.createElement('canvas');
canvasEl.id = this._oElement.id + '-canvas-container';
var oContainer = this._oElement.parentNode.insertBefore(canvasEl, this._oElement);
oContainer.width = this._oConfig.width;
oContainer.height = this._oConfig.height;
oContainer.style.width = this._oConfig.width + 'px';
oContainer.style.height = this._oConfig.height + 'px';
this._oContextContainer = oContainer.getContext('2d');
};
Canvas.Element.prototype._createCanvasBackground = function() {
var canvasEl = document.createElement('canvas');
canvasEl.id = this._oElement.id + '-canvas-background';
var oBackground = this._oElement.parentNode.insertBefore(canvasEl, this._oElement);
oBackground.width = this._oConfig.width;
oBackground.height = this._oConfig.height;
oBackground.style.width = this._oConfig.width + 'px';
oBackground.style.height = this._oConfig.height + 'px';
this._oContextBackground = oBackground.getContext('2d');
};
Canvas.Element.prototype.setCanvasBackground = function(oImg) {
this._backgroundImg = oImg;
var originalImgSize = oImg.getOriginalSize();
this._oContextBackground.drawImage(oImg._oElement, 0, 0, originalImgSize.width, originalImgSize.height);
};
Canvas.Element.prototype.onMouseUp = function(e) {
if (this._aImages == null) {
return;
}
if (this._currentTransform) {
this._currentTransform.target.setImageCoords();
}
if (this._currentTransform != null && this._currentTransform.action == "rotate") {
this.onRotateComplete.fire(e);
} else if (this._currentTransform != null && this._currentTransform.action == "drag") {
this.onDragComplete.fire(e);
}
this._currentTransform = null;
this._groupSelector = null;
this.renderTop();
};
Canvas.Element.prototype.onMouseDown = function(e) {
var mp = this.findMousePosition(e);
if (this._currentTransform != null || this._aImages == null) {
return;
}
var oImg = this.findTargetImage(mp, false);
if (!oImg) {
this._groupSelector = { ex: mp.ex, ey: mp.ey,
top: 0, left: 0 };
}
else {
var action = (!this.findTargetCorner(mp, oImg)) ? 'drag' : 'rotate';
if (action == "rotate") {
this.onRotateMove.fire(e);
} else if (action == "drag") {
this.onDragMove.fire(e);
}
this._prevTransform=this._currentTransform = {
target: oImg,
action: action,
scalex: oImg.scalex,
offsetX: mp.ex - oImg.left,
offsetY: mp.ey - oImg.top,
ex: mp.ex, ey: mp.ey,
left: oImg.left, top: oImg.top,
theta: oImg.theta
};
$('canvas_menu').style.transform='rotate('+oImg.theta*180/3.14+'deg)';
$('canvas_menu').style.left=oImg.left+"px";
$('canvas_menu').style.top=oImg.top+"px";
$('canvas_menu').style.display="block";
this.renderAll(false,false);
}
};
Canvas.Element.prototype.onMouseMove = function(e) {
var mp = this.findMousePosition(e);
if (this._aImages == null) {
return;
}
if (this._groupSelector != null) {
this._groupSelector.left = mp.ex - this._groupSelector.ex;
this._groupSelector.top = mp.ey - this._groupSelector.ey;
this.renderTop();
}
else if (this._currentTransform == null) {
var targetImg = this.findTargetImage(mp, true);
this.setCursor(mp, targetImg);
}
else {
if (this._currentTransform.action == 'rotate') {
this.rotateImage(mp);
this.scaleImage(mp);
this.onRotateMove.fire(e);
}
else {
this.translateImage(mp);
this.onDragMove.fire(e);
}
this.renderTop();
}
};
Canvas.Element.prototype.translateImage = function(mp) {
this._currentTransform.target.left = mp.ex - this._currentTransform.offsetX;
this._currentTransform.target.top = mp.ey - this._currentTransform.offsetY;
$('canvas_menu').style.left=this._currentTransform.target.left+"px";
$('canvas_menu').style.top=this._currentTransform.target.top +"px";
};
Canvas.Element.prototype.scaleImage = function(mp) {
var lastLen =
Math.sqrt(Math.pow(this._currentTransform.ey - this._currentTransform.top, 2) +
Math.pow(this._currentTransform.ex - this._currentTransform.left, 2));
var curLen =
Math.sqrt(Math.pow(mp.ey - this._currentTransform.top, 2) +
Math.pow(mp.ex - this._currentTransform.left, 2));
var curScalex= this._currentTransform.scalex * (curLen / lastLen);
var curScaley=this._currentTransform.target.scalex;
if(curScalex>0.7&&curScaley>0.7){
this._currentTransform.target.scalex =curScalex;
this._currentTransform.target.scaley = curScaley;
}
};
Canvas.Element.prototype.rotateImage = function(mp) {
var lastAngle = Math.atan2(
this._currentTransform.ey - this._currentTransform.top,
this._currentTransform.ex - this._currentTransform.left
);

var curAngle = Math.atan2(
mp.ey - this._currentTransform.top,
mp.ex - this._currentTransform.left
);
this._currentTransform.target.theta = (curAngle - lastAngle) + this._currentTransform.theta;
this.curAngle=this._currentTransform.target.theta*180/3.14;
$('canvas_menu').style.transform='rotate('+this.curAngle+'deg)';
};
Canvas.Element.prototype.setCursor = function(mp, targetImg) {
if (!targetImg) {
this._oElement.style.cursor = 'default';
}
else {
var corner = this.findTargetCorner(mp, targetImg);
if (!corner)
{
this._oElement.style.cursor = 'default';
}
else
{
if(corner == 'tr') {
this._oElement.style.cursor = 'ne-resize';
}
else if(corner == 'br') {
this._oElement.style.cursor = 'se-resize';
}
else if(corner == 'bl') {
this._oElement.style.cursor = 'sw-resize';
}
else if(corner == 'tl') {
this._oElement.style.cursor = 'nw-resize';
}
else {
this._oElement.style.cursor = 'default';
}
}
}
};
Canvas.Element.prototype.addImage = function(oImg) {
if(S.isEmptyObject(this._aImages)) {
this._aImages = [];
}
this._aImages.push(oImg);
this.renderAll(false,true);</p> <p> };
Canvas.Element.prototype.renderAll = function(allOnTop,allowCorners) {
var containerCanvas = (allOnTop) ? this._oContextTop : this._oContextContainer;
this._oContextTop.clearRect(0,0,parseInt(this._oConfig.width), parseInt(this._oConfig.height));
containerCanvas.clearRect(0,0,parseInt(this._oConfig.width), parseInt(this._oConfig.height));
if (allOnTop) {
var originalImgSize = this._backgroundImg.getOriginalSize();
this._oContextTop.drawImage(this._backgroundImg._oElement, 0, 0, originalImgSize.width, originalImgSize.height);
}
for (var i = 0, l = this._aImages.length-1; i < l; i += 1) {
this.drawImageElement(containerCanvas, this._aImages[i],allowCorners);
}
this.drawImageElement(this._oContextTop, this._aImages[this._aImages.length-1],allowCorners);
};
Canvas.Element.prototype.renderTop = function() {
this._oContextTop.clearRect(0,0,parseInt(this._oConfig.width), parseInt(this._oConfig.height));
this.drawImageElement(this._oContextTop, this._aImages[this._aImages.length-1],true);
if (this._groupSelector != null) {
this._oContextTop.fillStyle = "rgba(0, 0, 200, 0.5)";
this._oContextTop.fillRect(
this._groupSelector.ex - ((this._groupSelector.left > 0) ?
0 : - this._groupSelector.left),
this._groupSelector.ey - ((this._groupSelector.top > 0) ?
0 : - this._groupSelector.top),
Math.abs(this._groupSelector.left),
Math.abs(this._groupSelector.top)
);
this._oContextTop.strokeRect(
this._groupSelector.ex - ((this._groupSelector.left > 0) ?
0 : Math.abs(this._groupSelector.left)),
this._groupSelector.ey - ((this._groupSelector.top > 0) ?
0 : Math.abs(this._groupSelector.top)),
Math.abs(this._groupSelector.left),
Math.abs(this._groupSelector.top)
);
}
};
Canvas.Element.prototype.drawImageElement = function(context, oImg,allowCorners) {
oImg.cornervisibility=allowCorners;
var offsetY = oImg.height / 2;
var offsetX = oImg.width / 2;
context.save();
context.translate(oImg.left, oImg.top);
context.rotate(oImg.theta);
context.scale(oImg.scalex, oImg.scaley);
this.drawBorder(context, oImg, offsetX, offsetY);
var originalImgSize = oImg.getOriginalSize();
var polaroidHeight = ((oImg.height - originalImgSize.height) - (oImg.width - originalImgSize.width))/2;
context.drawImage(
oImg._oElement,

  • 竞博体育app下载 ,originalImgSize.width/2,
    ((- originalImgSize.height)/2 - polaroidHeight),
    originalImgSize.width,
    originalImgSize.height
    );
    if (oImg.cornervisibility) {
    this.drawCorners(context, oImg, offsetX, offsetY);
    }
    context.restore();
    };
    Canvas.Element.prototype._getImageLines = function(oCoords) {
    return {
    topline: {
    o: oCoords.tl,
    d: oCoords.tr
    },
    rightline: {
    o: oCoords.tr,
    d: oCoords.br
    },
    bottomline: {
    o: oCoords.br,
    d: oCoords.bl
    },
    leftline: {
    o: oCoords.bl,
    d: oCoords.tl
    }
    };
    };
    Canvas.Element.prototype.findTargetImage = function(mp, hovering) {
    for (var i = this._aImages.length-1; i >= 0; i -= 1) {
    var iLines = this._getImageLines(this._aImages[i].oCoords);
    var xpoints = this._findCrossPoints(mp, iLines);
    if (xpoints % 2 == 1 && xpoints != 0) {
    var target = this._aImages[i];
    if (!hovering) {
    this._aImages.splice(i, 1);
    this._aImages.push(target);
    }
    return target;
    }
    }
    return false;
    };
    Canvas.Element.prototype._findCrossPoints = function(mp, oCoords) {
    var b1, b2, a1, a2, xi, yi;
    var xcount = 0;
    var iLine = null;
    for (lineKey in oCoords) {
    iLine = oCoords[lineKey];
    if ((iLine.o.y < mp.ey) && (iLine.d.y < mp.ey)) {
    continue;
    }
    if ((iLine.o.y >= mp.ey) && (iLine.d.y >= mp.ey)) {
    continue;
    }
    if ((iLine.o.x == iLine.d.x) && (iLine.o.x >= mp.ex)) {
    xi = iLine.o.x;
    yi = mp.ey;
    }
    else {
    b1 = 0;
    b2 = (iLine.d.y-iLine.o.y)/(iLine.d.x-iLine.o.x);
    a1 = mp.ey-b1*mp.ex;
    a2 = iLine.o.y-b2*iLine.o.x;
    xi = - (a1-a2)/(b1-b2);
    yi = a1+b1*xi;
    }
    if (xi >= mp.ex) {
    xcount += 1;
    }
    if (xcount == 2) {
    break;
    }
    }
    return xcount;
    };
    Canvas.Element.prototype.findTargetCorner = function(mp, oImg) {
    var xpoints = null;
    var corners = ['tl','tr','br','bl'];
    for (var i in oImg.oCoords) {
    xpoints = this._findCrossPoints(mp, this._getImageLines(oImg.oCoords[i].corner));
    if (xpoints % 2 == 1 && xpoints != 0) {
    return i;
    }
    }
    return false;
    };
    Canvas.Element.prototype.findMousePosition = function(e) {
    var parentNode = (e.srcElement) ? e.srcElement.parentNode : e.target.parentNode;
    var isSafari2 = !S.support.ie&&!S.support.firefox;
    var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    var safariOffsetLeft = (isSafari2) ? e.target.ownerDocument.body.offsetLeft + scrollLeft : 0;
    var safariOffsetTop = (isSafari2) ? e.target.ownerDocument.body.offsetTop + scrollTop : 0;
    return {
    ex: e.clientX + scrollLeft - parentNode.offsetLeft - safariOffsetLeft,
    ey: e.clientY + scrollTop - parentNode.offsetTop - safariOffsetTop,
    screenX: e.screenX,
    screenY: e.screenY
    };
    };
    Canvas.Element.prototype.drawBorder = function(context, oImg, offsetX, offsetY) {
    var outlinewidth = 2;
    context.fillStyle = 'rgba(0, 0, 0, .3)';
    context.fillRect(-2 - offsetX, -2 - offsetY, oImg.width + (2 * outlinewidth), oImg.height + (2 * outlinewidth));
    context.fillStyle = '#fff';
    context.fillRect(-offsetX, -offsetY, oImg.width, oImg.height);
    };
    Canvas.Element.prototype.drawCorners = function(context, oImg, offsetX, offsetY) {
    context.fillStyle = "rgba(0, 200, 50, 0.5)";
    context.fillRect(-offsetX, -offsetY, oImg.cornersize, oImg.cornersize);
    context.fillRect(oImg.width - offsetX - oImg.cornersize, -offsetY, oImg.cornersize, oImg.cornersize);
    context.fillRect(-offsetX, oImg.height - offsetY - oImg.cornersize, oImg.cornersize, oImg.cornersize);
    context.fillRect(oImg.width - offsetX - oImg.cornersize, oImg.height - offsetY - oImg.cornersize, oImg.cornersize, oImg.cornersize);
    };
    Canvas.Element.prototype.clearCorners = function(context, oImg, offsetX, offsetY) {
    context.clearRect(-offsetX, -offsetY, oImg.cornersize, oImg.cornersize);
    context.clearRect(oImg.width - offsetX - oImg.cornersize, -offsetY, oImg.cornersize, oImg.cornersize);
    context.clearRect(-offsetX, oImg.height - offsetY - oImg.cornersize, oImg.cornersize, oImg.cornersize);
    context.clearRect(oImg.width - offsetX - oImg.cornersize, oImg.height - offsetY - oImg.cornersize, oImg.cornersize, oImg.cornersize);
    context.restore();
    };
    Canvas.Element.prototype.canvasTo = function(format) {
    this.renderAll(true,false);
    var containerCanvas =this._oContextTop;
    for (var i = 0, l = this._aImages.length; i < l; i += 1) {
    var offsetY = this._aImages[i].height / 2;
    var offsetX = this._aImages[i].width / 2;
    this.clearCorners(containerCanvas, this._aImages[i], offsetX, offsetY);
    }
    if (format == 'jpeg' || format == 'png') {
    return this._oElement.toDataURL('image/'+format);
    }
    };
    Canvas.CustomEvent = function(type) {
    this.type = type;
    this.scope = null;
    this.handler = null;
    var self = this;
    this.fire = function(e) {
    if(this.handler != null) {
    self.handler.call(self.scope, e);
    }
    };
    };
    }());
    return Canvas;
    });

canvasImg.js代码如下:

代码如下:

define('canvasImg', [ '../multi_upload/core' ], function(S) {
var Canvas = window.Canvas || {};
(function () {
Canvas.Img = function(el, oConfig) {
this._initElement(el);
this._initConfig(oConfig);
this.setImageCoords();
};
Canvas.Img.CSS_CANVAS = "canvas-img";
var DEFAULT_CONFIG = {
"TOP": {
key: "top",
value: 10
},
"LEFT": {
key: "left",
value: 10
},
"ANGLE": {
key: "angle",
value: 0
},
"THETA": {
key: "theta",
value: 0
},
"SCALE-X": {
key: "scalex",
value: 1
},
"SCALE-Y": {
key: "scaley",
value: 1
},
"CORNERSIZE": {
key: "cornersize",
value:10
},
"BORDERWIDTH": {
key: "borderwidth",
value: 10
},
"POLAROIDHEIGHT": {
key: "polaroidheight",
value: 40
},
"RANDOMPOSITION": {
key: "randomposition",
value: true
}
};
Canvas.Img.prototype._oElement = null;
Canvas.Img.prototype.top = null;
Canvas.Img.prototype.left = null;
Canvas.Img.prototype.maxwidth = null;
Canvas.Img.prototype.maxheight = null;
Canvas.Img.prototype.oCoords = null;
Canvas.Img.prototype.angle = null;
Canvas.Img.prototype.theta = null;
Canvas.Img.prototype.scalex = null;
Canvas.Img.prototype.scaley = null;
Canvas.Img.prototype.cornersize = null;
Canvas.Img.prototype.polaroidheight = null;
Canvas.Img.prototype.randomposition = null;
Canvas.Img.prototype.selected = false;
Canvas.Img.prototype.bordervisibility = false;
Canvas.Img.prototype.cornervisibility = false;
Canvas.Img.prototype._initElement = function(el) {
this._oElement = el;
};
Canvas.Img.prototype._initConfig = function(oConfig) {
var sKey;
for (sKey in DEFAULT_CONFIG) {
var defaultKey = DEFAULT_CONFIG[sKey].key;
if (!oConfig.hasOwnProperty(defaultKey)) { // = !(defaultKey in oConfig)
this[defaultKey] = DEFAULT_CONFIG[sKey].value;
}
else {
this[defaultKey] = oConfig[defaultKey];
}
}
if (this.bordervisibility) {
this.currentBorder = this.borderwidth;
}
else {
this.currentBorder = 0;
}
var normalizedSize = this.getNormalizedSize(this._oElement, parseInt(oConfig.maxwidth), parseInt(oConfig.maxheight));
this._oElement.width = normalizedSize.width;
this._oElement.height = normalizedSize.height;
this.width = normalizedSize.width + (2 * this.currentBorder);
this.height = normalizedSize.height + (2 * this.currentBorder);
if (this.randomposition) {
this._setRandomProperties(oConfig);
}
this.theta = this.angle * (Math.PI/180);
};
Canvas.Img.prototype.getNormalizedSize = function(oImg, maxwidth, maxheight) {
if (maxheight && maxwidth && (oImg.width > oImg.height && (oImg.width / oImg.height) < (maxwidth / maxheight))) {
normalizedWidth = Math.floor((oImg.width * maxheight) / oImg.height);
normalizedHeight = maxheight;
}
else if (maxheight && ((oImg.height == oImg.width) || (oImg.height > oImg.width) || (oImg.height > maxheight))) {
normalizedWidth = Math.floor((oImg.width * maxheight) / oImg.height);
normalizedHeight = maxheight;
}
else if (maxwidth && (maxwidth < oImg.width)){
normalizedHeight = Math.floor((oImg.height * maxwidth) / oImg.width);
normalizedWidth = maxwidth;
}
else {
normalizedWidth = oImg.width;
normalizedHeight = oImg.height;
}
return { width: normalizedWidth, height: normalizedHeight }
},
Canvas.Img.prototype.getOriginalSize = function() {
return { width: this._oElement.width, height: this._oElement.height }
};
Canvas.Img.prototype._setRandomProperties = function(oConfig) {
if (oConfig.angle == null) {
this.angle = (Math.random() * 90);
}
if (oConfig.top == null) {
this.top = this.height / 2 + Math.random() * 450;
}
if (oConfig.left == null) {
this.left = this.width / 2 + Math.random() * 600;
}
};
Canvas.Img.prototype.setCornersVisibility = function(visible) {
this.cornervisibility = visible;
};
Canvas.Img.prototype.setImageCoords = function() {
this.left = parseInt(this.left);
this.top = parseInt(this.top);
this.currentWidth = parseInt(this.width) * this.scalex;
this.currentHeight = parseInt(this.height) * this.scalex;
this._hypotenuse = Math.sqrt(Math.pow(this.currentWidth / 2, 2) + Math.pow(this.currentHeight / 2, 2));
this._angle = Math.atan(this.currentHeight / this.currentWidth);
var offsetX = Math.cos(this._angle + this.theta) * this._hypotenuse;
var offsetY = Math.sin(this._angle + this.theta) * this._hypotenuse;
var theta = this.theta;
var sinTh = Math.sin(theta);
var cosTh = Math.cos(theta);
var tl = {
x: this.left - offsetX,
y: this.top - offsetY
};
var tr = {
x: tl.x + (this.currentWidth * cosTh),
y: tl.y + (this.currentWidth * sinTh)
};
var br = {
x: tr.x - (this.currentHeight * sinTh),
y: tr.y + (this.currentHeight * cosTh)
};
var bl = {
x: tl.x - (this.currentHeight * sinTh),
y: tl.y + (this.currentHeight * cosTh)
};
this.oCoords = { tl: tl, tr: tr, br: br, bl: bl };
this.setCornerCoords();
};
Canvas.Img.prototype.setCornerCoords = function() {
var coords = this.oCoords;
var theta = this.theta;
var cosOffset = this.cornersize * this.scalex * Math.cos(theta);
var sinOffset = this.cornersize * this.scalex * Math.sin(theta);
coords.tl.corner = {
tl: {
x: coords.tl.x,
y: coords.tl.y
},
tr: {
x: coords.tl.x + cosOffset,
y: coords.tl.y + sinOffset
},
bl: {
x: coords.tl.x - sinOffset,
y: coords.tl.y + cosOffset
}
};
coords.tl.corner.br = {
x: coords.tl.corner.tr.x - sinOffset,
y: coords.tl.corner.tr.y + cosOffset
};

coords.tr.corner = {
tl: {
x: coords.tr.x - cosOffset,
y: coords.tr.y - sinOffset
},
tr: {
x: coords.tr.x,
y: coords.tr.y
},
br: {
x: coords.tr.x - sinOffset,
y: coords.tr.y + cosOffset
}
};
coords.tr.corner.bl = {
x: coords.tr.corner.tl.x - sinOffset,
y: coords.tr.corner.tl.y + cosOffset
};

coords.bl.corner = {
tl: {
x: coords.bl.x + sinOffset,
y: coords.bl.y - cosOffset
},
bl: {
x: coords.bl.x,
y: coords.bl.y
},
br: {
x: coords.bl.x + cosOffset,
y: coords.bl.y + sinOffset
}
};
coords.bl.corner.tr = {
x: coords.bl.corner.br.x + sinOffset,
y: coords.bl.corner.br.y - cosOffset
};

coords.br.corner = {
tr: {
x: coords.br.x + sinOffset,
y: coords.br.y - cosOffset
},
bl: {
x: coords.br.x - cosOffset,
y: coords.br.y - sinOffset
},
br: {
x: coords.br.x,
y: coords.br.y
}
};
coords.br.corner.tl = {
x: coords.br.corner.bl.x + sinOffset,
y: coords.br.corner.bl.y - cosOffset
};
};
}());
return Canvas;
});

puzzle.html代码如下:

代码如下:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link type="text/css" href="html5_puzzle.css" rel="stylesheet" />
<script type="text/javascript" src="../multi_upload/seed.js"></script>
<script type="text/javascript" src='html5_puzzle.js'></script>
</head>
<body>
<div id='html5_puzzle'>
<div id='puzzle_left'>
<div class='puzzle_column'>
<ul>
<li><img src='small_img/1.jpg' data-index='1' /></li>
<li><img src='small_img/2.jpg' data-index='2' /></li>
<li><img src='small_img/3.jpg' data-index='3' /></li>
<li><img src='small_img/4.jpg' data-index='4' /></li>
<li><img src='small_img/5.jpg' data-index='5' /></li>
</ul>
</div>
<div class='puzzle_column'>
<ul>
<li><img src='small_img/6.jpg' data-index='6' /></li>
<li><img src='small_img/7.jpg' data-index='7' /></li>
<li><img src='small_img/8.jpg' data-index='8' /></li>
<li><img src='small_img/9.jpg' data-index='9' /></li>
<li><img src='small_img/10.jpg' data-index='10' /></li>
</ul>
</div>
</div>
<div id='puzzle_right'>
<div id='puzzle_canvas'>
<canvas id="canvid1"></canvas>
<div id='canvas_menu'>
<a href='javascript:void(0)' id='photo_delete'>删除</a> <a
href='javascript:void(0)' id='photo_update'>更改图片</a>
</div>
</div>
<img id="bg" src="big_img/1.jpg" width='600' height='450' />
</div>
<div id='puzzle_bottom'>
<a href='javascript:void(0)' id='add_img'><span>添加图片</span><input
type="file" multiple="" id='fileImage'> </a> <a
href='javascript:void(0)' id='upload_btn'>上传</a> <a>点击图片可以旋转,拖拽,
缩放哦!</a>
</div>
</div>
<input type="file" id='test'>
<canvas id='test_canvas'></canvas>
</body>
</html>

html5_puzzle.css代码如下:

代码如下:

@CHARSET "UTF-8";</p> <p>#html5_puzzle {
font-size: 0;
}</p> <p>canvas {
background-color: transparent;
left: 0;
position: absolute;
top: 0;
}</p> <p>.puzzle_column,#puzzle_left,#puzzle_right,#add_img {
display: inline-block;
}</p> <p>.puzzle_column li {
display: block;
margin: 5px;
border: 1px solid #ffffff;
}</p> <p>.puzzle_column li:hover {
border: 1px solid #3B5998;
cursor: pointer;
}</p> <p>.puzzle_column {
font-size: 0;
}</p> <p>#puzzle_left,#puzzle_right {
border: 1px solid #3B5998;
}</p> <p>#puzzle_right,#puzzle_bottom a {
font-size: 14px;
margin: 10px 0 0 10px;
}</p> <p>#puzzle_bottom {
margin: 5px 0;
}</p> <p>#puzzle_canvas img {

}</p> <p>#puzzle_canvas {
overflow: hidden;
width: 600px;
height: 450px;
position: relative;
}</p> <p>#add_img input {
position: absolute;
font-size: 100px;
right: 0;
top: 0;
opacity: 0;
}</p> <p>#add_img {
position: relative;
display: inline-block;
background: #3B5998;
border-radius: 4px;
padding: 4px 12px;
overflow: hidden;
color: #ffffff;
}</p> <p>#bg,#show_list {
display: none;
}</p> <p>#canvas_menu {
border: 1px solid red;
position: absolute;
z-index: 5;
top: 0;
left: 0;
display: none;
}</p> <p>#canvas_menu a {
display: inline-block;
}</p> <p>#test_canvas {
top: 700px;
}

html5_puzzle.js代码如下:

代码如下:

require([ 'img_upload', '../puzzle/canvasImg', '../puzzle/canvasElement' ], function(
S, canvasImg, canvasElement) {
var img=[];
var canvas = new canvasElement.Element();
canvas.init('canvid1', {
width : 600,
height : 450
});
S('.puzzle_column img').on('click',function(e){
var index=this.getAttribute('data-index');
$('bg').onload = function() {
var ctx=$('canvid1-canvas-background').getContext('2d');
ctx.clearRect(0, 0,600,450);
img[0]=new canvasImg.Img($('bg'), {});
canvas.setCanvasBackground(img[0]);
};
$('bg').setAttribute('src','medium_img/'+index+'.jpg');
e.stopPropagation();
});
var CanvasDemo = function() {
return {
init : function() {
var img_list=dom.query('#puzzle_canvas img');
img[0]=new canvasImg.Img($('bg'), {});
S.each(img_list,function(i,el){
el.setAttribute('data-index',i);
img.push(new canvasImg.Img(el, {}));
canvas.addImage(img[i+1]);
});
canvas.setCanvasBackground(img[0]);
this.cornersvisible = (this.cornersvisible) ? false : true;
this.modifyImages(function(image) {
image.setCornersVisibility(this.cornersvisible);
});
},
modifyImages : function(fn) {
for ( var i =0, l = canvas._aImages.length; i < l; i += 1) {
fn.call(this, canvas._aImages[i]);
}
canvas.renderAll(false,false);
S('#puzzle_canvas img').remove();
img = [];
}
};
}();
function getCurImg(){
var oImg=canvas._prevTransform.target;
for(var i=0;i<canvas._aImages.length;i++){
if(canvas._aImages[i]._oElement.src==oImg._oElement.src){
return i;
}
}
}
S('#photo_delete').on('click',function(e){
var i=getCurImg();
canvas._aImages.splice(i,1);
canvas.renderAll(true,true);
$('canvas_menu').style.display="none";
});
S('#photo_update').on('click',function(e){
$('test').click();
});
S('#test').on('change',function(e){
var files = e.target.files || e.dataTransfer.files;
var reader = new FileReader();
reader.onload = (function() {
return function(e) {
var dataURL = e.target.result, canvas1 = document.querySelector('#test_canvas'), ctx = canvas1.getContext('2d'), img = new Image();
img.onload = function(e) {
if(img.width>200||img.height>200){
var prop=Math.min(200/img.width,200/img.height);
img.width=img.width*prop;
img.height=img.height*prop;
}
canvas1.width=img.width;
canvas1.height=img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
S('#canvid1').html(S('#canvid1').html()+"<img src='"+canvas1.toDataURL("image/jpeg")+"'/>");
var t = window.setTimeout(function() {
var i=getCurImg(),target=canvas._prevTransform.target;
console.log(target);
canvas._aImages[i]=new canvasImg.Img(dom.query('#canvid1 img')[0], {
top:target.top,
left:target.left,
scalex:target.scalex,
scaley:target.scaley,
angle:canvas.curAngle
});
canvas.renderTop();
clearTimeout(t);
S('#canvid1 img').remove();
},1000);
};
img.src = dataURL;
};
})();
reader.readAsDataURL(files[0]);
});
S('#upload_btn').on('click',function(){
var imgData = canvas.canvasTo('jpeg');
var imgValue = imgData.substr(22);
S.ajax({
url : '',
type : 'POST',
data : {
imgData : imgValue,
file_name :'mix_img.jpeg'
},
dataType : 'text',
success : function(data) {
alert("s");
}
});
});
});

至于用html5 input读取图片,这很简单就不贴出来了。

希望本文所述对大家的HTML5程序设计有所帮助。

html5版canvas自由拼图,html5canvas拼图

效果:

竞博体育app下载 2

 

canvasElement.js

  1 define('canvasElement', [ '../multi_upload/core' ], function(S) {
  2 var Canvas = window.Canvas || {};
  3 (function () {
  4     Canvas.Element = function() {};    
  5     Canvas.Element.prototype.fillBackground = true;
  6     Canvas.Element.prototype.showcorners = false;
  7     Canvas.Element.prototype.photoborder = true;
  8     Canvas.Element.prototype.polaroid = false;
  9     Canvas.Element.prototype._backgroundImg = null;
 10     Canvas.Element.prototype._groupSelector = null;
 11     Canvas.Element.prototype._aImages = null;
 12     Canvas.Element.prototype._oContext = null;
 13     Canvas.Element.prototype._oElement = null;
 14     Canvas.Element.prototype._oConfig = null;
 15     Canvas.Element.prototype._currentTransform = null;
 16     Canvas.Element.prototype._prevTransform = null;
 17     Canvas.Element.prototype.curAngle = null;
 18     Canvas.Element.prototype.init = function(el, oConfig) {
 19         if (el == '') {
 20             return;
 21         }
 22         this._initElement(el);
 23         this._initConfig(oConfig);
 24         this._createCanvasBackground();
 25         this._createContainer();
 26         this._initEvents();
 27         this._initCustomEvents();
 28     };
 29     Canvas.Element.prototype._initElement = function(el) {
 30         this._oElement = document.getElementById(el);
 31         this._oContextTop = this._oElement.getContext('2d');
 32     };
 33     Canvas.Element.prototype._initCustomEvents = function() {
 34         this.onRotateStart = new Canvas.CustomEvent('onRotateStart');
 35         this.onRotateMove = new Canvas.CustomEvent('onRotateMove');        
 36         this.onRotateComplete = new Canvas.CustomEvent('onRotateComplete');
 37         this.onDragStart = new Canvas.CustomEvent('onDragStart');    
 38         this.onDragMove = new Canvas.CustomEvent('onDragMove');
 39         this.onDragComplete = new Canvas.CustomEvent('onDragComplete');
 40     };
 41     Canvas.Element.prototype._initConfig = function(oConfig) {
 42         this._oConfig = oConfig;
 43         this._oElement.width = this._oConfig.width;
 44         this._oElement.height = this._oConfig.height;
 45         this._oElement.style.width = this._oConfig.width + 'px';
 46         this._oElement.style.height = this._oConfig.height + 'px';
 47     };
 48     Canvas.Element.prototype._initEvents = function() {
 49         var _this=this;
 50         S(this._oElement).on('mousedown',function(e){
 51              _this.onMouseDown(e);
 52         });
 53         S(this._oElement).on( 'mouseup', function(e){
 54             _this.onMouseUp(e);
 55         });
 56         S(this._oElement).on('mousemove', function(e){
 57             _this.onMouseMove(e);
 58         });
 59     };
 60     Canvas.Element.prototype._createContainer = function() {
 61         var canvasEl = document.createElement('canvas');
 62         canvasEl.id = this._oElement.id + '-canvas-container';
 63         var oContainer = this._oElement.parentNode.insertBefore(canvasEl, this._oElement);
 64         oContainer.width = this._oConfig.width;
 65         oContainer.height = this._oConfig.height;
 66         oContainer.style.width = this._oConfig.width + 'px';
 67         oContainer.style.height = this._oConfig.height + 'px';
 68         this._oContextContainer = oContainer.getContext('2d'); 
 69     };
 70     Canvas.Element.prototype._createCanvasBackground = function() {
 71         var canvasEl = document.createElement('canvas');
 72         canvasEl.id = this._oElement.id + '-canvas-background';
 73         var oBackground = this._oElement.parentNode.insertBefore(canvasEl, this._oElement);
 74         oBackground.width = this._oConfig.width;
 75         oBackground.height = this._oConfig.height;
 76         oBackground.style.width = this._oConfig.width + 'px';
 77         oBackground.style.height = this._oConfig.height + 'px';
 78         this._oContextBackground = oBackground.getContext('2d'); 
 79     };
 80     Canvas.Element.prototype.setCanvasBackground = function(oImg) {
 81         this._backgroundImg = oImg;
 82         var originalImgSize = oImg.getOriginalSize();
 83         this._oContextBackground.drawImage(oImg._oElement, 0, 0, originalImgSize.width, originalImgSize.height);
 84     };
 85     Canvas.Element.prototype.onMouseUp = function(e) {
 86         if (this._aImages == null) {
 87             return;
 88         }
 89         if (this._currentTransform) {
 90             this._currentTransform.target.setImageCoords();
 91         }
 92         if (this._currentTransform != null && this._currentTransform.action == "rotate") {
 93             this.onRotateComplete.fire(e);
 94         } else if (this._currentTransform != null && this._currentTransform.action == "drag") {
 95             this.onDragComplete.fire(e);
 96         }
 97         this._currentTransform = null;
 98         this._groupSelector = null;
 99         this.renderTop();
100     };
101     Canvas.Element.prototype.onMouseDown = function(e) {
102         var mp = this.findMousePosition(e);
103         if (this._currentTransform != null || this._aImages == null) {
104             return;
105         }
106         var oImg = this.findTargetImage(mp, false);
107         if (!oImg) {
108             this._groupSelector = { ex: mp.ex, ey: mp.ey,
109                                      top: 0, left: 0 };
110         }
111         else { 
112             var action = (!this.findTargetCorner(mp, oImg)) ? 'drag' : 'rotate';
113             if (action == "rotate") {
114                 this.onRotateMove.fire(e);
115             } else if (action == "drag") {
116                 this.onDragMove.fire(e);
117             }
118             this._prevTransform=this._currentTransform = { 
119                 target: oImg,
120                 action: action,
121                 scalex: oImg.scalex,
122                 offsetX: mp.ex - oImg.left,
123                 offsetY: mp.ey - oImg.top,
124                 ex: mp.ex, ey: mp.ey,
125                 left: oImg.left, top: oImg.top,
126                 theta: oImg.theta 
127             };
128             $('canvas_menu').style.transform='rotate('+oImg.theta*180/3.14+'deg)';
129             $('canvas_menu').style.left=oImg.left+"px";
130             $('canvas_menu').style.top=oImg.top+"px";
131             $('canvas_menu').style.display="block";
132             this.renderAll(false,false);
133         }
134     };
135     Canvas.Element.prototype.onMouseMove = function(e) {
136         var mp = this.findMousePosition(e);
137         if (this._aImages == null) {
138             return;
139         }
140         if (this._groupSelector != null) {
141             this._groupSelector.left = mp.ex - this._groupSelector.ex;
142             this._groupSelector.top = mp.ey - this._groupSelector.ey;
143             this.renderTop();
144         }
145         else if (this._currentTransform == null) {
146             var targetImg = this.findTargetImage(mp, true);
147             this.setCursor(mp, targetImg);
148         }
149         else {
150             if (this._currentTransform.action == 'rotate') {
151                 this.rotateImage(mp);
152                 this.scaleImage(mp);
153                 this.onRotateMove.fire(e);
154             }        
155             else {
156                 this.translateImage(mp);
157                 this.onDragMove.fire(e);
158             }
159             this.renderTop();
160         }        
161     };
162     Canvas.Element.prototype.translateImage = function(mp) {
163         this._currentTransform.target.left = mp.ex - this._currentTransform.offsetX;
164         this._currentTransform.target.top = mp.ey - this._currentTransform.offsetY;
165         $('canvas_menu').style.left=this._currentTransform.target.left+"px";
166         $('canvas_menu').style.top=this._currentTransform.target.top +"px";
167     };
168     Canvas.Element.prototype.scaleImage = function(mp) {
169         var lastLen = 
170             Math.sqrt(Math.pow(this._currentTransform.ey - this._currentTransform.top, 2) +
171             Math.pow(this._currentTransform.ex - this._currentTransform.left, 2));
172         var curLen = 
173             Math.sqrt(Math.pow(mp.ey - this._currentTransform.top, 2) +
174             Math.pow(mp.ex - this._currentTransform.left, 2));
175         var curScalex= this._currentTransform.scalex * (curLen / lastLen);
176         var curScaley=this._currentTransform.target.scalex;
177         if(curScalex>0.7&&curScaley>0.7){
178             this._currentTransform.target.scalex =curScalex;
179             this._currentTransform.target.scaley = curScaley;
180         }
181     };
182     Canvas.Element.prototype.rotateImage = function(mp) {
183         var lastAngle = Math.atan2(
184                 this._currentTransform.ey - this._currentTransform.top,
185                 this._currentTransform.ex - this._currentTransform.left
186         );
187         
188         var curAngle = Math.atan2(
189             mp.ey - this._currentTransform.top,
190             mp.ex - this._currentTransform.left
191         );
192         this._currentTransform.target.theta = (curAngle - lastAngle) + this._currentTransform.theta;
193         this.curAngle=this._currentTransform.target.theta*180/3.14;
194         $('canvas_menu').style.transform='rotate('+this.curAngle+'deg)';
195     };
196     Canvas.Element.prototype.setCursor = function(mp, targetImg) {
197         if (!targetImg) {
198             this._oElement.style.cursor = 'default';
199         }
200         else { 
201             var corner = this.findTargetCorner(mp, targetImg);
202             if (!corner) 
203             {
204                 this._oElement.style.cursor = 'default';
205             }
206             else
207             {
208                 if(corner == 'tr') {
209                     this._oElement.style.cursor = 'ne-resize';
210                 }
211                 else if(corner == 'br') {
212                     this._oElement.style.cursor = 'se-resize';
213                 }
214                 else if(corner == 'bl') {
215                     this._oElement.style.cursor = 'sw-resize';
216                 }
217                 else if(corner == 'tl') {
218                     this._oElement.style.cursor = 'nw-resize';
219                 }                                    
220                 else {
221                     this._oElement.style.cursor = 'default';
222                 }
223             }
224         }
225     };
226     Canvas.Element.prototype.addImage = function(oImg) {
227         if(S.isEmptyObject(this._aImages)) {
228             this._aImages = [];
229         }
230         this._aImages.push(oImg);
231         this.renderAll(false,true);
232 
233     };
234     Canvas.Element.prototype.renderAll = function(allOnTop,allowCorners) {
235         var containerCanvas = (allOnTop) ? this._oContextTop : this._oContextContainer;
236         this._oContextTop.clearRect(0,0,parseInt(this._oConfig.width), parseInt(this._oConfig.height));
237         containerCanvas.clearRect(0,0,parseInt(this._oConfig.width), parseInt(this._oConfig.height));
238         if (allOnTop) {
239             var originalImgSize = this._backgroundImg.getOriginalSize();
240             this._oContextTop.drawImage(this._backgroundImg._oElement, 0, 0, originalImgSize.width, originalImgSize.height);
241         }
242             for (var i = 0, l = this._aImages.length-1; i < l; i += 1) {
243                 this.drawImageElement(containerCanvas, this._aImages[i],allowCorners);            
244             }
245             this.drawImageElement(this._oContextTop, this._aImages[this._aImages.length-1],allowCorners);
246     };
247     Canvas.Element.prototype.renderTop = function() {
248         this._oContextTop.clearRect(0,0,parseInt(this._oConfig.width), parseInt(this._oConfig.height));
249         this.drawImageElement(this._oContextTop, this._aImages[this._aImages.length-1],true);
250         if (this._groupSelector != null) {
251             this._oContextTop.fillStyle = "rgba(0, 0, 200, 0.5)";
252             this._oContextTop.fillRect(
253                 this._groupSelector.ex - ((this._groupSelector.left > 0) ?
254                     0 : - this._groupSelector.left), 
255                 this._groupSelector.ey - ((this._groupSelector.top > 0) ? 
256                     0 : - this._groupSelector.top), 
257                 Math.abs(this._groupSelector.left), 
258                 Math.abs(this._groupSelector.top)
259             );
260             this._oContextTop.strokeRect(
261                 this._groupSelector.ex - ((this._groupSelector.left > 0) ? 
262                     0 : Math.abs(this._groupSelector.left)), 
263                 this._groupSelector.ey - ((this._groupSelector.top > 0) ? 
264                     0 : Math.abs(this._groupSelector.top)), 
265                 Math.abs(this._groupSelector.left), 
266                 Math.abs(this._groupSelector.top)
267             );
268         }
269     };
270     Canvas.Element.prototype.drawImageElement = function(context, oImg,allowCorners) {
271         oImg.cornervisibility=allowCorners;
272         var offsetY = oImg.height / 2;
273         var offsetX = oImg.width / 2;
274         context.save();
275         context.translate(oImg.left, oImg.top);
276         context.rotate(oImg.theta);
277         context.scale(oImg.scalex, oImg.scaley);
278         this.drawBorder(context, oImg, offsetX, offsetY);
279         var originalImgSize = oImg.getOriginalSize();
280         var polaroidHeight = ((oImg.height - originalImgSize.height) - (oImg.width - originalImgSize.width))/2;
281         context.drawImage(
282             oImg._oElement, 
283             - originalImgSize.width/2,  
284             ((- originalImgSize.height)/2 - polaroidHeight), 
285             originalImgSize.width, 
286             originalImgSize.height
287         );
288         if (oImg.cornervisibility) {
289             this.drawCorners(context, oImg, offsetX, offsetY);
290         }
291         context.restore();
292     };
293     Canvas.Element.prototype._getImageLines = function(oCoords) {
294         return {
295             topline: { 
296                 o: oCoords.tl,
297                 d: oCoords.tr 
298             },
299             rightline: { 
300                 o: oCoords.tr,
301                 d: oCoords.br 
302             },
303             bottomline: { 
304                 o: oCoords.br,
305                 d: oCoords.bl 
306             },
307             leftline: { 
308                 o: oCoords.bl,
309                 d: oCoords.tl 
310             }
311         };
312     };
313     Canvas.Element.prototype.findTargetImage = function(mp, hovering) {
314         for (var i = this._aImages.length-1; i >= 0; i -= 1) {
315             var iLines = this._getImageLines(this._aImages[i].oCoords);
316             var xpoints = this._findCrossPoints(mp, iLines);
317             if (xpoints % 2 == 1 && xpoints != 0) {
318                 var target = this._aImages[i];
319                 if (!hovering) {
320                     this._aImages.splice(i, 1);
321                     this._aImages.push(target);
322                 }
323                 return target;
324             }
325         }
326         return false;
327     };    
328     Canvas.Element.prototype._findCrossPoints = function(mp, oCoords) {
329         var b1, b2, a1, a2, xi, yi;
330         var xcount = 0;
331         var iLine = null;
332         for (lineKey in oCoords) {
333             iLine = oCoords[lineKey];
334             if ((iLine.o.y < mp.ey) && (iLine.d.y < mp.ey)) {
335                 continue;
336             }
337             if ((iLine.o.y >= mp.ey) && (iLine.d.y >= mp.ey)) {
338                 continue;
339             }
340             if ((iLine.o.x == iLine.d.x) && (iLine.o.x >= mp.ex)) { 
341                 xi = iLine.o.x;
342                 yi = mp.ey;
343             }
344             else {
345                 b1 = 0; 
346                 b2 = (iLine.d.y-iLine.o.y)/(iLine.d.x-iLine.o.x); 
347                 a1 = mp.ey-b1*mp.ex;
348                 a2 = iLine.o.y-b2*iLine.o.x;
349                 xi = - (a1-a2)/(b1-b2); 
350                 yi = a1+b1*xi; 
351             }
352             if (xi >= mp.ex) { 
353                 xcount += 1;
354             }
355             if (xcount == 2) {
356                 break;
357             }
358         }
359         return xcount;
360     };
361     Canvas.Element.prototype.findTargetCorner = function(mp, oImg) {
362         var xpoints = null;
363         var corners = ['tl','tr','br','bl'];
364         for (var i in oImg.oCoords) {
365             xpoints = this._findCrossPoints(mp, this._getImageLines(oImg.oCoords[i].corner));
366             if (xpoints % 2 == 1 && xpoints != 0) {
367                 return i;
368             }        
369         }
370         return false;
371     };
372     Canvas.Element.prototype.findMousePosition = function(e) {
373         var parentNode = (e.srcElement) ? e.srcElement.parentNode : e.target.parentNode;
374         var isSafari2 = !S.support.ie&&!S.support.firefox;
375         var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
376         var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
377         var safariOffsetLeft = (isSafari2) ? e.target.ownerDocument.body.offsetLeft + scrollLeft : 0;
378         var safariOffsetTop = (isSafari2) ? e.target.ownerDocument.body.offsetTop + scrollTop : 0;
379         return {
380             ex: e.clientX + scrollLeft - parentNode.offsetLeft - safariOffsetLeft,
381             ey: e.clientY + scrollTop - parentNode.offsetTop - safariOffsetTop,
382             screenX: e.screenX,
383             screenY: e.screenY
384         };
385     };
386     Canvas.Element.prototype.drawBorder = function(context, oImg, offsetX, offsetY) {
387         var outlinewidth = 2;
388         context.fillStyle = 'rgba(0, 0, 0, .3)';
389         context.fillRect(-2 - offsetX, -2 - offsetY, oImg.width + (2 * outlinewidth), oImg.height + (2 * outlinewidth));
390         context.fillStyle = '#fff';
391         context.fillRect(-offsetX, -offsetY, oImg.width, oImg.height);
392     };
393     Canvas.Element.prototype.drawCorners = function(context, oImg, offsetX, offsetY) {
394         context.fillStyle = "rgba(0, 200, 50, 0.5)";
395         context.fillRect(-offsetX, -offsetY, oImg.cornersize, oImg.cornersize);
396         context.fillRect(oImg.width - offsetX - oImg.cornersize, -offsetY, oImg.cornersize, oImg.cornersize);
397         context.fillRect(-offsetX, oImg.height - offsetY - oImg.cornersize, oImg.cornersize, oImg.cornersize);
398         context.fillRect(oImg.width - offsetX - oImg.cornersize, oImg.height - offsetY - oImg.cornersize, oImg.cornersize, oImg.cornersize);
399     };
400     Canvas.Element.prototype.clearCorners = function(context, oImg, offsetX, offsetY) {
401         context.clearRect(-offsetX, -offsetY, oImg.cornersize, oImg.cornersize);
402         context.clearRect(oImg.width - offsetX - oImg.cornersize, -offsetY, oImg.cornersize, oImg.cornersize);
403         context.clearRect(-offsetX, oImg.height - offsetY - oImg.cornersize, oImg.cornersize, oImg.cornersize);
404         context.clearRect(oImg.width - offsetX - oImg.cornersize, oImg.height - offsetY - oImg.cornersize, oImg.cornersize, oImg.cornersize);
405         context.restore();
406     };
407     Canvas.Element.prototype.canvasTo = function(format) {
408         this.renderAll(true,false);
409         var containerCanvas =this._oContextTop;
410         for (var i = 0, l = this._aImages.length; i < l; i += 1) {
411             var offsetY = this._aImages[i].height / 2;
412             var offsetX = this._aImages[i].width / 2;
413             this.clearCorners(containerCanvas, this._aImages[i], offsetX, offsetY);
414         }
415         if (format == 'jpeg' || format == 'png') {
416             return this._oElement.toDataURL('image/'+format);
417         }
418     };    
419     Canvas.CustomEvent = function(type) {
420         this.type = type;
421         this.scope = null;
422         this.handler = null;
423         var self = this;
424         this.fire = function(e) {
425             if(this.handler != null) {
426                 self.handler.call(self.scope, e);
427             }
428         };
429     };    
430 }());
431 return Canvas;
432 });

canvasImg.js

  1 define('canvasImg', [ '../multi_upload/core' ], function(S) {
  2 var Canvas = window.Canvas || {};
  3 (function () {
  4     Canvas.Img = function(el, oConfig) {
  5         this._initElement(el);
  6         this._initConfig(oConfig);
  7         this.setImageCoords();
  8     };
  9     Canvas.Img.CSS_CANVAS = "canvas-img";
 10     var DEFAULT_CONFIG = {    
 11         "TOP": { 
 12             key: "top", 
 13             value: 10 
 14         },
 15         "LEFT": { 
 16             key: "left", 
 17             value: 10
 18         },        
 19         "ANGLE": { 
 20             key: "angle", 
 21             value: 0  
 22         },
 23         "THETA": { 
 24             key: "theta", 
 25             value: 0  
 26         },
 27         "SCALE-X": { 
 28             key: "scalex", 
 29             value: 1
 30         },
 31         "SCALE-Y": { 
 32             key: "scaley", 
 33             value: 1
 34         },
 35         "CORNERSIZE": { 
 36             key: "cornersize", 
 37             value:10
 38         },
 39         "BORDERWIDTH": { 
 40             key: "borderwidth", 
 41             value: 10
 42         },
 43         "POLAROIDHEIGHT": {
 44             key: "polaroidheight",
 45             value: 40
 46         },
 47         "RANDOMPOSITION": {
 48             key: "randomposition",
 49             value: true
 50         }
 51     };
 52     Canvas.Img.prototype._oElement = null;
 53     Canvas.Img.prototype.top = null;
 54     Canvas.Img.prototype.left = null;
 55     Canvas.Img.prototype.maxwidth = null;
 56     Canvas.Img.prototype.maxheight = null;
 57     Canvas.Img.prototype.oCoords = null;
 58     Canvas.Img.prototype.angle = null;
 59     Canvas.Img.prototype.theta = null;
 60     Canvas.Img.prototype.scalex = null;
 61     Canvas.Img.prototype.scaley = null;
 62     Canvas.Img.prototype.cornersize = null;
 63     Canvas.Img.prototype.polaroidheight = null;
 64     Canvas.Img.prototype.randomposition = null;
 65     Canvas.Img.prototype.selected = false;
 66     Canvas.Img.prototype.bordervisibility = false;
 67     Canvas.Img.prototype.cornervisibility = false;
 68     Canvas.Img.prototype._initElement = function(el) {
 69             this._oElement = el;
 70     };
 71     Canvas.Img.prototype._initConfig = function(oConfig) {
 72         var sKey;
 73         for (sKey in DEFAULT_CONFIG) {
 74             var defaultKey = DEFAULT_CONFIG[sKey].key;
 75             if (!oConfig.hasOwnProperty(defaultKey)) { // = !(defaultKey in oConfig)
 76                 this[defaultKey] = DEFAULT_CONFIG[sKey].value;
 77             }
 78             else {
 79                 this[defaultKey] = oConfig[defaultKey];
 80             }
 81         }
 82         if (this.bordervisibility) {
 83             this.currentBorder = this.borderwidth;
 84         }
 85         else {
 86             this.currentBorder = 0;
 87         }
 88         var normalizedSize = this.getNormalizedSize(this._oElement, parseInt(oConfig.maxwidth), parseInt(oConfig.maxheight));
 89         this._oElement.width = normalizedSize.width;
 90         this._oElement.height = normalizedSize.height;
 91         this.width = normalizedSize.width + (2 * this.currentBorder);
 92         this.height = normalizedSize.height + (2 * this.currentBorder);
 93         if (this.randomposition) {
 94             this._setRandomProperties(oConfig);
 95         }
 96         this.theta = this.angle * (Math.PI/180);
 97     };
 98     Canvas.Img.prototype.getNormalizedSize = function(oImg, maxwidth, maxheight) {
 99         if (maxheight && maxwidth && (oImg.width > oImg.height && (oImg.width / oImg.height) < (maxwidth / maxheight))) {
100             normalizedWidth = Math.floor((oImg.width * maxheight) / oImg.height);
101             normalizedHeight = maxheight;
102         }
103         else if (maxheight && ((oImg.height == oImg.width) || (oImg.height > oImg.width) || (oImg.height > maxheight))) {
104             normalizedWidth = Math.floor((oImg.width * maxheight) / oImg.height);
105             normalizedHeight = maxheight;
106         }
107         else if (maxwidth && (maxwidth < oImg.width)){ 
108             normalizedHeight = Math.floor((oImg.height * maxwidth) / oImg.width);
109             normalizedWidth = maxwidth;
110         }
111         else {
112             normalizedWidth = oImg.width;
113             normalizedHeight = oImg.height;            
114         }
115         return { width: normalizedWidth, height: normalizedHeight }
116     },
117     Canvas.Img.prototype.getOriginalSize = function() {
118         return { width: this._oElement.width, height: this._oElement.height }
119     };
120     Canvas.Img.prototype._setRandomProperties = function(oConfig) {
121         if (oConfig.angle == null) {
122             this.angle = (Math.random() * 90);
123         }
124         if (oConfig.top == null) {
125             this.top = this.height / 2 + Math.random() * 450;
126         }
127         if (oConfig.left == null) {
128             this.left = this.width / 2 + Math.random() * 600;
129         }
130     };
131     Canvas.Img.prototype.setCornersVisibility = function(visible) {
132         this.cornervisibility = visible;
133     };
134     Canvas.Img.prototype.setImageCoords = function() {
135         this.left = parseInt(this.left);
136         this.top = parseInt(this.top);
137         this.currentWidth = parseInt(this.width) * this.scalex;
138         this.currentHeight = parseInt(this.height) * this.scalex;
139         this._hypotenuse = Math.sqrt(Math.pow(this.currentWidth / 2, 2) + Math.pow(this.currentHeight / 2, 2));
140         this._angle = Math.atan(this.currentHeight / this.currentWidth);
141         var offsetX = Math.cos(this._angle + this.theta) * this._hypotenuse;
142         var offsetY = Math.sin(this._angle + this.theta) * this._hypotenuse;
143         var theta = this.theta;
144         var sinTh = Math.sin(theta);
145         var cosTh = Math.cos(theta);
146         var tl = {
147             x: this.left - offsetX,
148             y: this.top - offsetY
149         };
150         var tr = {
151             x: tl.x + (this.currentWidth * cosTh),
152             y: tl.y + (this.currentWidth * sinTh)
153         };
154         var br = {
155             x: tr.x - (this.currentHeight * sinTh),
156             y: tr.y + (this.currentHeight * cosTh)
157         };
158         var bl = {
159             x: tl.x - (this.currentHeight * sinTh),
160             y: tl.y + (this.currentHeight * cosTh)
161         };
162         this.oCoords = { tl: tl, tr: tr, br: br, bl: bl };
163         this.setCornerCoords();            
164     };
165     Canvas.Img.prototype.setCornerCoords = function() {
166         var coords = this.oCoords;
167         var theta = this.theta;
168         var cosOffset = this.cornersize * this.scalex * Math.cos(theta);
169         var sinOffset = this.cornersize * this.scalex * Math.sin(theta);
170         coords.tl.corner = {
171             tl: {
172                 x: coords.tl.x,
173                 y: coords.tl.y
174             },
175             tr: {
176                 x: coords.tl.x + cosOffset,
177                 y: coords.tl.y + sinOffset
178             },
179             bl: {
180                 x: coords.tl.x - sinOffset,
181                 y: coords.tl.y + cosOffset
182             }
183         };
184         coords.tl.corner.br = {
185             x: coords.tl.corner.tr.x - sinOffset,
186             y: coords.tl.corner.tr.y + cosOffset
187         };
188         
189         coords.tr.corner = {
190             tl: {
191                 x: coords.tr.x - cosOffset,
192                 y: coords.tr.y - sinOffset
193             },
194             tr: {
195                 x: coords.tr.x,
196                 y: coords.tr.y
197             },
198             br: {
199                 x: coords.tr.x - sinOffset,
200                 y: coords.tr.y + cosOffset
201             }
202         };
203         coords.tr.corner.bl = {
204             x: coords.tr.corner.tl.x - sinOffset,
205             y: coords.tr.corner.tl.y + cosOffset
206         };
207         
208         coords.bl.corner = {
209             tl: {
210                 x: coords.bl.x + sinOffset,
211                 y: coords.bl.y - cosOffset
212             },
213             bl: {
214                 x: coords.bl.x,
215                 y: coords.bl.y
216             },
217             br: {
218                 x: coords.bl.x + cosOffset,
219                 y: coords.bl.y + sinOffset
220             }
221         };
222         coords.bl.corner.tr = {
223             x: coords.bl.corner.br.x + sinOffset,
224             y: coords.bl.corner.br.y - cosOffset
225         };
226         
227         coords.br.corner = {
228             tr: {
229                 x: coords.br.x + sinOffset,
230                 y: coords.br.y - cosOffset
231             },
232             bl: {
233                 x: coords.br.x - cosOffset,
234                 y: coords.br.y - sinOffset
235             },
236             br: {
237                 x: coords.br.x,
238                 y: coords.br.y
239             }
240         };
241         coords.br.corner.tl = {
242             x: coords.br.corner.bl.x + sinOffset,
243             y: coords.br.corner.bl.y - cosOffset
244         };
245     };
246 }());
247     return Canvas;
248 });

puzzle.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 5 <title>Insert title here</title>
 6 <link type="text/css" href="html5_puzzle.css" rel="stylesheet" />
 7 <script type="text/javascript" src="../multi_upload/seed.js"></script>
 8 <script type="text/javascript" src='html5_puzzle.js'></script>
 9 </head>
10 <body>
11     <div id='html5_puzzle'>
12         <div id='puzzle_left'>
13             <div class='puzzle_column'>
14                 <ul>
15                     <li><img src='small_img/1.jpg' data-index='1' /></li>
16                     <li><img src='small_img/2.jpg' data-index='2' /></li>
17                     <li><img src='small_img/3.jpg' data-index='3' /></li>
18                     <li><img src='small_img/4.jpg' data-index='4' /></li>
19                     <li><img src='small_img/5.jpg' data-index='5' /></li>
20                 </ul>
21             </div>
22             <div class='puzzle_column'>
23                 <ul>
24                     <li><img src='small_img/6.jpg' data-index='6' /></li>
25                     <li><img src='small_img/7.jpg' data-index='7' /></li>
26                     <li><img src='small_img/8.jpg' data-index='8' /></li>
27                     <li><img src='small_img/9.jpg' data-index='9' /></li>
28                     <li><img src='small_img/10.jpg' data-index='10' /></li>
29                 </ul>
30             </div>
31         </div>
32         <div id='puzzle_right'>
33             <div id='puzzle_canvas'>
34                 <canvas id="canvid1"></canvas>
35                 <div id='canvas_menu'>
36                     <a href='javascript:void(0)' id='photo_delete'>删除</a> <a
37                         href='javascript:void(0)' id='photo_update'>更改图片</a>
38                 </div>
39             </div>
40             <img id="bg" src="big_img/1.jpg" width='600' height='450' />
41         </div>
42         <div id='puzzle_bottom'>
43             <a href='javascript:void(0)' id='add_img'>添加图片<input
44                 type="file" multiple="" id='fileImage'> </a> <a
45                 href='javascript:void(0)' id='upload_btn'>上传</a> <a>点击图片可以旋转,拖拽,
46                 缩放哦!</a>
47         </div>
48     </div>
49     <input type="file" id='test'>
50     <canvas id='test_canvas'></canvas>
51 </body>
52 </html>

html5_puzzle.css

 1 @CHARSET "UTF-8";
 2 
 3 #html5_puzzle {
 4     font-size: 0;
 5 }
 6 
 7 canvas {
 8     background-color: transparent;
 9     left: 0;
10     position: absolute;
11     top: 0;
12 }
13 
14 .puzzle_column,#puzzle_left,#puzzle_right,#add_img {
15     display: inline-block;
16 }
17 
18 .puzzle_column li {
19     display: block;
20     margin: 5px;
21     border: 1px solid #ffffff;
22 }
23 
24 .puzzle_column li:hover {
25     border: 1px solid #3B5998;
26     cursor: pointer;
27 }
28 
29 .puzzle_column {
30     font-size: 0;
31 }
32 
33 #puzzle_left,#puzzle_right {
34     border: 1px solid #3B5998;
35 }
36 
37 #puzzle_right,#puzzle_bottom a {
38     font-size: 14px;
39     margin: 10px 0 0 10px;
40 }
41 
42 #puzzle_bottom {
43     margin: 5px 0;
44 }
45 
46 #puzzle_canvas img {
47     
48 }
49 
50 #puzzle_canvas {
51     overflow: hidden;
52     width: 600px;
53     height: 450px;
54     position: relative;
55 }
56 
57 #add_img input {
58     position: absolute;
59     font-size: 100px;
60     right: 0;
61     top: 0;
62     opacity: 0;
63 }
64 
65 #add_img {
66     position: relative;
67     display: inline-block;
68     background: #3B5998;
69     border-radius: 4px;
70     padding: 4px 12px;
71     overflow: hidden;
72     color: #ffffff;
73 }
74 
75 #bg,#show_list {
76     display: none;
77 }
78 
79 #canvas_menu {
80     border: 1px solid red;
81     position: absolute;
82     z-index: 5;
83     top: 0;
84     left: 0;
85     display: none;
86 }
87 
88 #canvas_menu a {
89     display: inline-block;
90 }
91 
92 #test_canvas {
93     top: 700px;
94 }

html5_puzzle.js

  1 require([ 'img_upload', '../puzzle/canvasImg', '../puzzle/canvasElement' ], function(
  2         S, canvasImg, canvasElement) {
  3     var img=[];
  4     var canvas = new canvasElement.Element();
  5     canvas.init('canvid1', {
  6         width : 600,
  7         height : 450
  8     });
  9     S('.puzzle_column img').on('click',function(e){
 10         var index=this.getAttribute('data-index');
 11         $('bg').onload = function() {
 12             var ctx=$('canvid1-canvas-background').getContext('2d');
 13             ctx.clearRect(0, 0,600,450);
 14             img[0]=new canvasImg.Img($('bg'), {});
 15             canvas.setCanvasBackground(img[0]);
 16         };
 17         $('bg').setAttribute('src','medium_img/'+index+'.jpg');
 18         e.stopPropagation();
 19     });
 20     var CanvasDemo = function() {
 21         return {
 22             init : function() {
 23                 var img_list=dom.query('#puzzle_canvas img');
 24                 img[0]=new canvasImg.Img($('bg'), {});
 25                 S.each(img_list,function(i,el){
 26                         el.setAttribute('data-index',i);
 27                         img.push(new canvasImg.Img(el, {}));
 28                         canvas.addImage(img[i+1]);
 29                 });
 30                 canvas.setCanvasBackground(img[0]);
 31                 this.cornersvisible = (this.cornersvisible) ? false : true;
 32                 this.modifyImages(function(image) {
 33                     image.setCornersVisibility(this.cornersvisible);
 34                 });
 35             },
 36             modifyImages : function(fn) {
 37                 for ( var i =0, l = canvas._aImages.length; i < l; i += 1) {
 38                     fn.call(this, canvas._aImages[i]);
 39                 }
 40                 canvas.renderAll(false,false);
 41                 S('#puzzle_canvas img').remove();
 42                 img = [];
 43             }
 44         };
 45     }();
 46     function getCurImg(){
 47         var oImg=canvas._prevTransform.target;
 48         for(var i=0;i<canvas._aImages.length;i++){
 49         if(canvas._aImages[i]._oElement.src==oImg._oElement.src){
 50             return i;
 51         }
 52         }
 53     }
 54     S('#photo_delete').on('click',function(e){
 55         var i=getCurImg();
 56         canvas._aImages.splice(i,1);
 57         canvas.renderAll(true,true);
 58         $('canvas_menu').style.display="none";
 59     });
 60     S('#photo_update').on('click',function(e){
 61         $('test').click();
 62     });
 63     S('#test').on('change',function(e){
 64         var files = e.target.files || e.dataTransfer.files;
 65         var reader = new FileReader();
 66         reader.onload = (function() {
 67             return function(e) {
 68         var dataURL = e.target.result, canvas1 = document.querySelector('#test_canvas'), ctx = canvas1.getContext('2d'), img = new Image();
 69         img.onload = function(e) {
 70             if(img.width>200||img.height>200){
 71                 var prop=Math.min(200/img.width,200/img.height);
 72                 img.width=img.width*prop;
 73                 img.height=img.height*prop;
 74             }
 75             canvas1.width=img.width;
 76             canvas1.height=img.height;
 77             ctx.drawImage(img, 0, 0, img.width, img.height);
 78             S('#canvid1').html(S('#canvid1').html()+"<img src='"+canvas1.toDataURL("image/jpeg")+"'/>");
 79             var t = window.setTimeout(function() {
 80                 var i=getCurImg(),target=canvas._prevTransform.target;
 81                 console.log(target);
 82                 canvas._aImages[i]=new canvasImg.Img(dom.query('#canvid1 img')[0], {
 83                     top:target.top,
 84                     left:target.left,
 85                     scalex:target.scalex,
 86                     scaley:target.scaley,
 87                     angle:canvas.curAngle
 88                 });
 89                 canvas.renderTop();
 90                 clearTimeout(t);
 91                 S('#canvid1 img').remove();
 92             },1000);
 93         };
 94         img.src = dataURL;
 95             };
 96         })();
 97         reader.readAsDataURL(files[0]);
 98     });
 99     S('#upload_btn').on('click',function(){
100         var imgData = canvas.canvasTo('jpeg');
101         var imgValue = imgData.substr(22);
102         S.ajax({
103             url : 'http://localhost/html5/upload1.php',
104             type : 'POST',
105             data : {
106                 imgData : imgValue,
107                 file_name :'mix_img.jpeg'
108             },
109             dataType : 'text',
110             success : function(data) {
111                 alert("s");
112             }
113         });
114     });
115 });

至于用html5 input读取图片,这很简单就不贴出来了

Document

您好,教您一个html5 canvas的问题: 我在canvas中画了多个图形,有图像(image)、直线

canvas可以实现
首先canvas要响应鼠标事件(onmousedown之类)
之后所有的图形必须要创建相应的对象,来记录他们所在的位置以及大小还有zOrder(层叠位置,在2个对象重叠的时候决定谁在上面),相应的对象放到一个数组里并按zOrder排序
当canvas的鼠标click事件触发后,按照zOrder的顺序来检测鼠标坐标在不在某个对象的区域里,如果在,则执行相应的函数  

body{background:black; overflow: hidden;}

html5 canvas 怎让矩形倾斜 如图

html:
<canvas id="c" width="400px" height="400px">not support</canvas>CSS:
#c{ background-color:rgba(134, 179, 225, 1);}JS:
window.onload = init;var ctx = null;var recX = 150, recY = 150, angle = -35;function init() { var cvs = document.getElementById('c'); ctx = cvs.getContext('2d'); drawRectangle(); drawCircle(-100, 0, 50, '#fff'); drawCircle(100, 0, 50, 'rgba(134, 179, 225, 1)');}function setPos() { ctx.translate(recX, recY); ctx.rotate(angle * Math.PI / 180);}function drawRectangle() { ctx.save(); setPos(); ctx.fillStyle = '#fff'; ctx.fillRect(-100, -50, 200, 100); ctx.restore();}function drawCircle(x, y, r, fillStyle) { ctx.save(); ctx.beginPath(); setPos(); ctx.fillStyle = fillStyle; ctx.arc(x, y, r, 0, Math.PI * 2, true); ctx.closePath(); ctx.fill(); ctx.restore();}  

效果: canvasElement.js 1 define('canvasElement', [ '../multi_upload/core' ], function (S) { 2 var Canvas = window.Canvas || {}; 3...

function getRandom(min, max){

return Math.floor(Math.random()*(max-min)+min);

}

function Canvas(){

this.pos = [];

this.numMax = 768;

this.width = window.innerWidth;

this.height = window.innerHeight;

this.rx = this.width/2;

this.ry=this.height/2;

this.cxt;

this.v = 1.25; //点的速度

this.dcolor=2;

}

//创建节点、设置属性、获取对象

Canvas.prototype.createEle = function(){

var ele = document.createElement("canvas");

ele.id = "canvas";

ele.value = "sorry,your browser can not support canvas!";

ele.width = this.width;

ele.height = this.height;

this.cxt = ele.getContext('2d');

document.body.appendChild(ele);

}

Canvas.prototype.setCircle = function(){

var color, flag;

for(var i=0; i

var r = ((i/128)+1 )*40; //距离圆心初始半径,一共6层

var rotate =  (i%128)*2.8125*(Math.PI/180); //一层128个,夹角2.8125

flag = i/128;

if( 0 <= flag && flag < 1.0){

color = 'rgb(255,0,'+(i%128)*canvas.dcolor+')';

}else if(1.0 <= flag && flag < 2.0){

color = 'rgb('+(255-(i%128)*canvas.dcolor)+',0,255)';

}else if(2.0 <= flag && flag < 3){

color = 'rgb(0,'+(i%128)*canvas.dcolor+',255)';

}else if(3 <= flag && flag < 4){

color = 'rgb(0,255,'+(255-(i%128)*canvas.dcolor)+')';

}else if(4 <= flag && flag < 5){

color = 'rgb('+(i%128)*canvas.dcolor+',255,0)';

}else if(5 <= flag && flag < 6){

color = 'rgb(255,'+(255-(i%128)*canvas.dcolor)+',0)';

}

this.pos[i] = {

r_max: 240, //6层间隔50,最大300

rotate: rotate,//所在点的相对角度

x: r*Math.cos(rotate)+this.width/2,

y: r*Math.sin(rotate)+this.height/2,

color: color,

}

}

}

Canvas.prototype.draw = function(x,y,r,color){

this.cxt.save();

this.cxt.beginPath();

this.cxt.fillStyle = color;

this.cxt.arc(x, y, r, 0, Math.PI*2, true);

this.cxt.fill();

this.cxt.restore();

}

Canvas.prototype.animate = function(){

var dx;

canvas.cxt.clearRect(0,0,canvas.width,canvas.height);

for(var i=0;i

dx = Math.sqrt(Math.pow(canvas.ry - canvas.pos[i].y, 2)+Math.pow(canvas.rx - canvas.pos[i].x, 2));

if( dx < 1 || dx > 300){

//重置位置

canvas.pos[i].x = canvas.pos[i].r_max*Math.cos(canvas.pos[i].rotate)+canvas.width/2;

canvas.pos[i].y = canvas.pos[i].r_max*Math.sin(canvas.pos[i].rotate)+canvas.height/2;

}

//速度

canvas.pos[i].vx = -canvas.v*Math.cos(canvas.pos[i].rotate);

canvas.pos[i].vy = -canvas.v*Math.sin(canvas.pos[i].rotate);

//移动

canvas.pos[i].x += canvas.pos[i].vx;

canvas.pos[i].y += canvas.pos[i].vy;

//大小渐变

canvas.pos[i].r = Math.sqrt(Math.pow(canvas.ry - canvas.pos[i].y, 2)+Math.pow(canvas.rx - canvas.pos[i].x, 2))/80;

canvas.draw(canvas.pos[i].x, canvas.pos[i].y, canvas.pos[i].r, canvas.pos[i].color);

}

window.requestAnimationFrame(canvas.animate);

}

Canvas.prototype.changeV = function(){

var count = 1;

setInterval(function(){

canvas.v = 1.25 * Math.pow(2, count);

if(count++ > 3) {count = 1;}

},5000);

}

var canvas = new Canvas();

canvas.createEle();

canvas.setCircle();

canvas.animate();

canvas.changeV();

���ų<���

交流:

  • 首页
  • 电话
  • 软件