[英]HTML5 canvas fill image with a circle
I was reading this post HTML5 canvas fill circle with image and was curious about doing something a little different.我正在阅读这篇文章HTML5 canvas 用图像填充圆圈,并对做一些不同的事情感到好奇。
Step by step I'd like to: 1. Take this image I have of a shield.一步一步我想: 1. 拿这张我有盾牌的图像。
2. Trace the outline of the shield to get the shape. 2. 描出盾牌的轮廓以获得形状。 3. Use a second, larger, image to fill the outline of the shield. 3. 使用第二个更大的图像来填充盾牌的轮廓。 I don't want it to fit.我不希望它适合。 I just want it to observe the boundaries set by the outline of the shield and not draw outside them.我只希望它观察盾牌轮廓设置的边界,而不是在它们之外绘制。
Here's what I have so far: JSFiddle - outline shape .这是我到目前为止所拥有的: JSFiddle - 轮廓形状。
var img = new Image();
img.crossOrigin = "anonymous";
img.onload = function () {
// draw the image
// (this time to grab the image's pixel data
ctx.drawImage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.height / 2);
// grab the image's pixel data
imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imgData.data;
// call the marching ants algorithm
// to get the outline path of the image
// (outline=outside path of transparent pixels
points = geom.contour(defineNonTransparent);
ctx.strokeStyle = "red";
ctx.lineWidth = 2;
redraw();
}
img.src = "https://cdn1.iconfinder.com/data/icons/shield-4/744/1-512.png";
// redraw the canvas
// user determines if original-image or outline path or both are visible
function redraw() {
// clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw the image
ctx.drawImage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.height / 2);
// draw the path (consisting of connected points)
// draw outline path
ctx.beginPath();
ctx.moveTo(points[0][0], points[0][1]);
for (var i = 1; i < points.length; i++) {
var point = points[i];
ctx.lineTo(point[0], point[1]);
}
ctx.closePath();
ctx.stroke();
ctx.fillStyle="yellow"; // Just filling with yellow temporarily but would like to use an image
ctx.fill();
}
I'm not sure how to draw inside the outline without overwriting it.我不确定如何在不覆盖轮廓的情况下绘制轮廓。
I figured it out using context save, clip, and restore.我使用上下文保存、剪辑和恢复来解决这个问题。 new jsfiddle新的 jsfiddle
ctx.save();
ctx.clip();
loadnewimage();
ctx.restore();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.