我开始学习画布,我刚刚遇到了我的第一个令人沮丧的情况,我试图制作一个三角形中的.jpg src的剪切蒙版。一切看起来都很好,直到我恢复我的上下文并尝试添加任何其他路径...我的剪贴蒙版似乎不存在了。
下面是我的代码:
<script>
function init() {
var canvas = document.getElementById('myCanvas');
if(canvas.getContext) {
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.src = 'stephgopro2.jpg';
// triangle coordonate
context.save();
context.beginPath;
context.moveTo(100, 0);
context.lineTo(0, 100);
context.lineTo(200, 100);
context.lineTo(100, 0);
context.clip();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0, 300, 170);
};
context.restore();
context.beginPath();
context.fillStyle = '#333';
context.rect(0, 0, 600, 200);
context.fill();
}
}
</script>
</head>
<body onload='init()'>
<canvas id="myCanvas" width="600" height="200"></canvas>
</body>你能帮帮我吗?非常感谢。
发布于 2012-11-23 05:14:22
图像是异步加载的,因此在将图像绘制到画布之前,已经恢复了上下文。如果您按如下方式更新代码,您将获得(我认为是)您期望的结果:
function init() {
var canvas = document.getElementById('myCanvas');
if(canvas.getContext) {
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.src = 'assets/1.jpg';
// triangle coordonate
context.save();
context.beginPath();
context.moveTo(100, 0);
context.lineTo(0, 100);
context.lineTo(200, 100);
context.lineTo(100, 0);
context.stroke();
context.clip();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0, 300, 170);
// Restore the context and continue drawing now the image has been drawn
context.restore();
context.beginPath();
context.fillStyle = '#333';
context.rect(0, 0, 600, 200);
context.fill();
};
}
}https://stackoverflow.com/questions/13517848
复制相似问题