[英]How can I give a background for an object on the canvas?
我做了一個小畫布,並用繪制moveto()和lineto()順序的路徑創建了一個正方形。
因此,我有一個帶有紅色邊框的正方形,並且可以使用fillStyle設置背景色,並使用fill()獲取顏色。
單擊執行。
var c = document.createElement('canvas');
c.id = 'myCanvas';
c.style.background = "#ffffff";
c.width = "100";
c.height = "50";
document.getElementById('container').appendChild(c);
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, 80);
ctx.lineTo(50, 80);
ctx.lineTo(50, 0);
ctx.lineTo(0, 0);
ctx.strokeStyle = "red";
ctx.stroke();
var getColor2 = 0;
var getColor = 0;
c.addEventListener("click", function(){
if(getColor2 == 0){
ctx.fillStyle = "#ffffff";
}
if(getColor2 == 1){
ctx.fillStyle = "#ff33df";
}
if(getColor2 == 2){
ctx.fillStyle = "#bbbbbb";
}
if(getColor2 == 3){
ctx.fillStyle = "#bb4563";
}
if(getColor2 == 4){
ctx.fillStyle = "#234556";
getColor2 = -1;
}
getColor2++;
ctx.fill();
});
https://jsfiddle.net/mafb7qhh/2/
我的問題是:當我單擊畫布時,它也會執行。 我只想通過單擊正方形來執行。
您在畫布上繪制的所有內容都無法“選擇”,因為它不像DOM元素那樣存在。 如果您需要一些可點擊的區域,也許可以使用SVG
代替畫布,或者在畫布上使用與您繪制的元素相同的位置/大小的不可見的dom元素來代替畫布
無論如何,我做了這個小jsfiddle ,從矩形列表中檢查鼠標是否結束,例如是否希望使用畫布處理鼠標事件(僅適用於矩形)。
對於更復雜的多邊形,您必須使用(例如) ray casting algorithm
。 https://zh.wikipedia.org/wiki/Point_in_polygon
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.