在这里,我尝试使用多个圆弧形状来制作圆。就像下面这样:
var startAngle = 0;
var arc = Math.PI / 6;
var ctx;
var leftValue=275;
var topValue=300;
var wheelImg = "/image/wwXlF.png";
function drawWheelImg()
{
var canvas = document.getElementById("canvas");
if(canvas.getContext)
{
var outsideRadius = 260;
var textRadius = 217;
var insideRadius = 202;
ctx = canvas.getContext("2d");
for(var i = 0; i < 12; i++)
{
var angle = startAngle + i * arc;
ctx.beginPath();
ctx.arc(leftValue, topValue, outsideRadius, angle, angle + arc, false);
ctx.arc(leftValue, topValue, insideRadius, angle + arc, angle, true);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.arc(leftValue, topValue, outsideRadius, angle, angle + arc, false);
ctx.shadowBlur=3;
ctx.shadowColor="#A47C15";
ctx.stroke();
ctx.closePath();
ctx.save();
ctx.translate(leftValue + Math.cos(angle + arc / 2) * textRadius,
topValue + Math.sin(angle + arc / 2) * textRadius);
ctx.rotate(angle + arc / 2 + Math.PI / 2);
var imgName = wheelImg;
var img = new Image();
img.src = wheelImg;
ctx.drawImage(img,-44, -25,50,40);
ctx.restore();
}
}
}
function spin()
{
drawWheelImg();
}
drawWheelImg();
<button class="btnSpin" onclick="spin();">Spin</button>
<canvas id="canvas" width="550" height="580"></canvas>
问题:
现在,问题是当页面加载时,我调用使用圆弧绘制圆的函数并将图像绘制到圆弧中。但这不起作用。
如果我在单击按钮时调用相同的函数,那么它就会工作并显示图像。
我找到了很多,但没有得到解决方案。不知道为什么图像在加载时不显示。
任何帮助将不胜感激。
最佳答案
这里的要点是,您应该等到图像加载后才能实际绘制它。
为了让你的代码正常工作,我最好的选择是将所有 Canvas 绘图包装到 image.onload 函数中,因为这样你就可以确保一旦你开始在上面实际绘图,它就会被渲染。
我将代码发布在工作 Plunkr 上
var startAngle = 0;
var arc = Math.PI / 6;
var ctx;
var leftValue = 275;
var topValue = 300;
var wheelImg = "/image/wwXlF.png";
function drawWheelImg() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var imgName = wheelImg;
var img = new Image();
img.src = wheelImg;
img.onload = function() {
var outsideRadius = 260;
var textRadius = 217;
var insideRadius = 202;
ctx = canvas.getContext("2d");
for (var i = 0; i < 12; i++) {
var angle = startAngle + i * arc;
ctx.beginPath();
ctx.arc(leftValue, topValue, outsideRadius, angle, angle + arc, false);
ctx.arc(leftValue, topValue, insideRadius, angle + arc, angle, true);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.arc(leftValue, topValue, outsideRadius, angle, angle + arc, false);
ctx.shadowBlur = 3;
ctx.shadowColor = "#A47C15";
ctx.stroke();
ctx.closePath();
ctx.save();
ctx.translate(leftValue + Math.cos(angle + arc / 2) * textRadius,
topValue + Math.sin(angle + arc / 2) * textRadius);
ctx.rotate(angle + arc / 2 + Math.PI / 2);
ctx.drawImage(img, -44, -25, 50, 40);
ctx.restore();
}
}
}
}
drawWheelImg();
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="550" height="400"></canvas>
<script src="script.js"></script>
</body>
</html>
关于javascript - 加载时 Canvas 图像不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34441361/