我一直在练习使用 Javascript 和 Canvas,并且遇到了一个问题,我正在渲染一个或两个形状以及几行来创建自定义形状。现在我需要能够单独为每个图像着色,但是当我使用 new Image(); 时对于第一个形状,纹理在绘制的最后一个 ctx 形状上渲染。
这是我的代码:
renderCanvas: function(topLength, heightLength, slant) {
var canvases = Array.from(document.getElementsByClassName("DesignerCanvas"));
for (var canvas of canvases) {
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = '#000';
ctx.lineWidth = 0.5;
// String for Hanging
ctx.beginPath();
ctx.rect(150, 0, 3, 75);
ctx.stroke();
ctx.closePath();
// Top Trimming
ctx.beginPath();
ctx.moveTo( ( 150 - ( topLength / 2 ) ) , 80 );
ctx.quadraticCurveTo( 150 , 70, 150 + ( topLength / 2 ), 80);
ctx.lineTo( 150 + ( topLength / 2 ), 83 );
ctx.quadraticCurveTo( 150 , 73, 150 - ( topLength / 2 ), 83);
ctx.closePath();
ctx.stroke();
// Shade Outter Body
ctx.beginPath();
ctx.moveTo( 150 + ( topLength / 2 ), 83 );
ctx.quadraticCurveTo( 150 , 73, 150 - (topLength / 2), 83);
ctx.lineTo( 150 - (( topLength / 2 ) + slant), heightLength );
ctx.quadraticCurveTo( 150 , ( heightLength - 10 ), 150 + ( (topLength / 2 ) + slant ), heightLength);
ctx.closePath();
ctx.stroke();
// Shade Inner Body
ctx.beginPath();
ctx.moveTo( 150 + ( (topLength / 2) + slant ), heightLength );
ctx.quadraticCurveTo( 150 , (heightLength - 10), 150 - ((topLength / 2) + slant ), heightLength);
ctx.quadraticCurveTo( 150 , (heightLength + 5), 150 + ((topLength / 2) + slant ), heightLength);
ctx.stroke();
ctx.closePath();
// Bottom Trimming
ctx.beginPath();
ctx.moveTo( 150 + ((topLength / 2) + slant ), (heightLength - 3) );
ctx.quadraticCurveTo( 150 , (heightLength - 15), 150 - ((topLength / 2) + slant ), (heightLength - 3));
ctx.lineTo( 150 - ((topLength / 2) + slant ), heightLength );
ctx.quadraticCurveTo( 150 , (heightLength + 5), 150 + ((topLength / 2) + slant ), heightLength);
ctx.closePath();
ctx.stroke();
}
},
init: function () {
console.log("Product Designer: Initialized.");
this.bindActions();
this.renderPage("DesignerTab1", "DesignerPanel1");
}
}
好吧,澄清一下,我的最终结果应该与现在基本相同,但能够更改我所做的所有路径的纹理背景。例如,第一个路径字符串应该能够填充图像,下一个路径顶部 trim 应该能够填充图像等等。
我的代码中的问题是,当您将图像放置到 new Image() 时,纹理将渲染在整个形状的底部,这不是我想要的,它应该只填充形状的顶部。
最佳答案
图像是异步加载的。图像的onload函数在renderCanvas函数完成后启动。当onload函数执行时,当前路径将是renderCanvas函数中定义的最后一个路径。要在所需路径内绘制图像,您需要将定义所需路径的代码移至 onload 函数内。例如,改变...
// String for Hanging
ctx.beginPath();
ctx.rect(150, 0, 3, 75);
var img = new Image();
img.src = 'image here';
img.onload = function() {
var pattern = ctx.createPattern(this,"repeat");
ctx.fillStyle = pattern;
ctx.fill();
};
ctx.closePath();
到...
// String for Hanging
var img = new Image();
img.src = 'image here';
img.onload = function() {
ctx.beginPath();
ctx.rect(150, 0, 3, 75);
var pattern = ctx.createPattern(this,"repeat");
ctx.fillStyle = pattern;
ctx.fill();
ctx.closePath();
};
关于javascript - 如何分离每个要单独填充的 HTML Canvas 路径/形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37253088/