【发布时间】:2021-05-27 23:36:29
【问题描述】:
我正在做一个项目,我需要在将近 5 个画布上绘制。我已经成功创建了第一个画布,但是当我输入第二个代码时,我只能在这个最新的画布上绘制。
我读到的问题可能是上下文(“2d”)我试图将保存在不同的 ctx 变量中,例如 ctx2 或类似的东西。
这是我的代码:
HTML
<!--First Canvas-->
<div class="col-sm-12 col-lg-6 mt-5 d-flex flex-column justify-content-center">
<div id="contenedor-pizarra-cervical" class="contenedor-pizarra mx-auto">
<canvas id="pizarra-cervical"></canvas>
</div>
</div>
<!--Second Canvas-->
<div class="col-sm-12 col-lg-6 mt-5 d-flex flex-column justify-content-center">
<div id="contenedor-pizarra-postural" class="contenedor-pizarra mx-auto">
<canvas id="pizarra-postural"></canvas>
</div>
</div>
第一个画布的 JS 工作正常:
//Canvas Cervical
var canvasCervical = document.getElementById("pizarra-cervical");
var ctx = canvasCervical.getContext("2d");
var painting = document.getElementById("contenedor-pizarra-cervical");
var paintStyle = getComputedStyle(painting);
canvasCervical.width = parseInt(paintStyle.getPropertyValue("width"));
canvasCervical.height = parseInt(paintStyle.getPropertyValue("height"));
var mouse = {x: 0, y: 0};
canvasCervical.addEventListener('mousemove', function(e){
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop
}, false);
ctx.lineWidth = 3;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = '#7baeb0';
canvasCervical.addEventListener('mousedown', function(e){
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvasCervical.addEventListener('mousemove', onPaint, false);
}, false);
canvasCervical.addEventListener('mouseup', function(){
canvasCervical.removeEventListener('mousemove', onPaint, false)
},false);
var onPaint = function (){
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};
【问题讨论】:
-
假设您通过 id 请求第二个画布?
document.getElementById("pizarra-postural");也许发布无效的代码?
标签: javascript html jquery canvas html5-canvas