简体   繁体   English

画布Javascript绘制功能不起作用

[英]Canvas Javascript draw function not working

I am trying to separate canvas context from the actual draw functions but not working. 我正在尝试将画布上下文与实际绘制功能分开,但无法正常工作。 As part of the context I wish to include the ability to resize the canvas which isn't working. 作为上下文的一部分,我希望包括调整无法使用的画布大小的功能。 The HTML works fine as this is evident with the getElementbyID working. HTML可以正常工作,因为getElementbyID可以正常工作。 The draw function which works fine is included for reference. 包括正常工作的绘图功能供参考。

window.onload = function() {
    'use strict';
    var ctx = getCanvas();
    draw(ctx);
}
function getCanvas() {
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var w = canvas.width = 200;
    var h = canvas.height = 150;
    return ctx;
}
function draw(ctx) {
    ctx.fillStyle = 'rgb(200, 0, 0)';
    ctx.fillRect(10, 10, 50, 50);
    ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
    ctx.fillRect(30, 30, 50, 50);
}

I see no issues with your code. 我认为您的代码没有问题。 It works as expected. 它按预期工作。

 window.onload = function() { 'use strict'; var ctx = getCanvas(); draw(ctx); }; function getCanvas() { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var w = canvas.width = 200; var h = canvas.height = 150; return ctx; } function draw(ctx) { ctx.fillStyle = 'rgb(200, 0, 0)'; ctx.fillRect(10, 10, 50, 50); ctx.fillStyle = 'rgba(0, 0, 200, 0.5)'; ctx.fillRect(30, 30, 50, 50); } 
 canvas{border: 1px solid black} 
 <canvas id="canvas" width="1000" height="1000"></canvas> 

note: do not set canvas­ 's width and height using css ( in first place ). 注意: 不要使用CSS( 排在首位 )设置画布宽度和高度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM