HTML5 画布 - 我的线条/弧线没有出现在图像顶部

HTML5 Canvas - my lines/arcs are not appearing on top of an image

本文关键字:顶部 图像 画布 我的 HTML5      更新时间:2023-09-26

我用lineTo()画了一些线,用arc()画了一些弧。我想画出我创造的这些形状,它们的黑色轮廓在我拥有的蓝色/白色背景上清晰可见。它很轻,所以我知道黑色会显示出来。但事实并非如此。

我用画布本身来放置背景图像,这是错的吗?以下是相关代码:

blueprint_background.onload = function(){
var pattern = context.createPattern(this, "repeat");
context.fillStyle = pattern;
context.rect(margin_x,margin_y,eff_width,eff_height);
context.fill();
};

还有我美丽的身材:

//the three sides of the triangle
context.beginPath();
context.moveTo(loc_x, loc_y);
context.lineTo(loc_x, loc_y + 30); //vertical downwards
context.moveTo(loc_x, loc_y);
context.lineTo(loc_x + 20, loc_y + 15);
context.moveTo(loc_x, loc_y + 30);
context.lineTo(loc_x + 20, loc_y + 15); //go the other way to complete the triangle
context.stroke(); 

顺便说一句,如果有人想对使用画布绘制形状的不良做法大声疾呼,请在它成为习惯之前去做。例如,在调用 stroke() 后,我想知道我是否应该调用 closePath() 方法或其他方法。

但是,是的,我的主要问题是我看不到图像背景顶部的黑线。

感谢您的任何帮助。

如果三角形的代码在背景onload部分之外,那么这可能会修复它:

blueprint_background.onload = function(){
    //background
    var pattern = context.createPattern(this, "repeat");
    context.fillStyle = pattern;
    context.rect(margin_x, margin_y, eff_width, eff_height);
    context.fill();
    draw_triangle();
};
function draw_triangle(){                       //seperate function
    //triangle
    context.beginPath():
    context.moveTo(loc_x, loc_y);
    context.lineTo(loc_x, loc_y + 30);
    context.moveTo(loc_x, loc_y);
    context.lineTo(loc_x + 20, loc_y + 15);
    context.moveTo(loc_x, loc_y + 30);
    context.lineTo(loc_x + 20, loc_y + 15);
    context.stroke(); 
};

这是因为您的背景必须等到加载,这将导致背景绘制在三角形顶部。