我想使用HTML5的canvas
标记和JavaScript在页面中裁剪多个图像。问题是页面只显示其中一个图像。
我该怎么办?我试过的代码如下:
<canvas id="myCanvas" width="300" height="300"></canvas>
<canvas id="myCanvas" width="300" height="300"></canvas>
<canvas id="myCanvas" width="300" height="300"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
// draw cropped image
var sourceX = 0;
var sourceY = 0;
var sourceWidth = 200;
var sourceHeight = 150;
var destWidth = sourceWidth;
var destHeight = sourceHeight;
var destX = canvas.width / 2 - destWidth / 2;
var destY = canvas.height / 2 - destHeight / 2;
context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
};
imageObj.src ='http://static.adzerk.net/Advertisers/3478c54721cd466fb6f7d3afe16e97d4.gif';
</script>
答案 0 :(得分:0)
就像Some Guy所说的那样,每个画布都使用相同的id
- 这是禁忌。尝试给每个人一个唯一的id
或使用一个类。
然后,这只是逐个抓取元素的问题 - 你可以do with JavaScript或者更容易使用jQuery(下面)。
查看this updated Fiddle或查看此JavaScript代码段:
var canvases = $('.myCanvas');
$(canvases).each(function () {
var canvas = $(this).get(0); //Grab the canvas node from the jQuery container.
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function () {
var sourceX = 0;
var sourceY = 0;
var sourceWidth = 200;
var sourceHeight = 150;
var destWidth = sourceWidth;
var destHeight = sourceHeight;
var destX = canvas.width / 2 - destWidth / 2;
var destY = canvas.height / 2 - destHeight / 2;
context.drawImage(imageObj, sourceX, sourceY,
sourceWidth, sourceHeight, destX,
destY, destWidth, destHeight);
};
imageObj.src = 'path/to/your/image.png';
});