gpt4 book ai didi

javascript - Q : HTML5 Canvas change background color

转载 作者:行者123 更新时间:2023-11-28 05:16:59 28 4
gpt4 key购买 nike

我只是想知道是否可以通过函数调用更改Canvas颜色?我有这个代码里面有圆圈我想改变外部颜色(背景):

var canvads = document.getElementById('canvas')
var context = canvas.getContext('2d');

function circle() {
var centerX = 0;
var centerY = 0;
var radius = 78;
context.clearRect(0, 0, window.innerWidth,window.innerHeight);

context.fillStyle = 'rgba(0,0,0,0.5)';
context.fillRect(0,0,window.innerWidth,window.innerHeight);

context.translate(canvas.width / 2, canvas.height / 2);

context.scale(1.5, 2);

context.beginPath();
context.arc(centerX, centerY, radius, 0, 5 * Math.PI, false);

context.lineWidth = 5;
context.stroke();

context.fillStyle = 'rgba(0,0,0,1)';

context.globalCompositeOperation = 'destination-out';
context.fill();

context.globalCompositeOperation = 'source-over';
}

function change_color() {
context.fillStyle = 'rgba(0,255,0,1)';
context.fill();
}

circle()

JsFiddle

最佳答案

您需要稍微改变方法 - 尽管在某种程度上可以“填充背景”,但 Canvas 的主要工作方式是不断重绘整个图像。在 HTML 游戏中,它每秒完成 X 次,但在较小的项目中,它通常应该在每个 Action 之后完成。所以,在你的情况下,像这样的事情应该可以解决问题:FIDDLE

var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d');

function initCanvas() {
context.clearRect(0, 0, window.innerWidth,window.innerHeight);

context.fillStyle = 'rgba(0,0,0,0.5)';
context.fillRect(0,0,window.innerWidth,window.innerHeight);
}

function circle() {
var centerX = 0;
var centerY = 0;
var radius = 78;

context.save()
context.translate(canvas.width / 2, canvas.height / 2);

context.scale(1.5, 2);

// define the arc path
context.beginPath();
context.arc(centerX, centerY, radius, 0, 5 * Math.PI, false);

// stroke it
context.lineWidth = 5;
context.stroke();

// make alpha solid (the color doesn't matter)
context.fillStyle = 'rgba(0,0,0,1)';

// change composite mode and fill
context.globalCompositeOperation = 'destination-out';
context.fill();
context.restore()

// reset composite mode to default
}

function changeColor() {
context.fillStyle = 'rgba(0,255,0,1)';
context.fillRect(0,0,window.innerWidth,window.innerHeight);

circle()
}

initCanvas()
circle()
document.querySelector('#but').addEventListener('click',changeColor)

并注意保存/恢复,尤其是在变换/旋转之后。此外,修复了 onclick。

关于javascript - Q : HTML5 Canvas change background color,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44127099/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com