Canvas lineTo()在错误的位置绘制y坐标

btf*_*btf 7 javascript canvas

我正在尝试使用ctx.lineTo()在画布上绘制一些矩形.它们被绘制但是y坐标永远不对.矩形变得太高,在y轴上的错误位置.当我逐步使用调试器时,它会将lineTo()方法中的y坐标显示为正确,但我创建了一个canvas.click事件以提醒坐标(当我点击左上角时它是正确的,它会发出警报(0) ,0)).click事件显示y坐标实际上不是它将在lineTo()方法中绘制的状态.但是,x坐标始终是正确的.有一点需要考虑的是我通过将jtml附加到带有javascript的元素来创建我的画布,然后我添加了一个我绘制的图像.我重新缩放矩形的坐标,使它们适当地放在画布上,缩放到适合设备大小的图像大小.这是我从画布创建到使用lineTo()方法的所有代码.

Canvas在此方法的早期阶段创建(在appendPicture()中):

function appendSection(theSection, list) {
    list.append('<label class="heading">' + theSection.description + '</label><br/><hr><br/>');
    if (theSection.picture) {
        appendPicture(list, theSection);
        var canvas = document.getElementById('assessmentImage');
        var ctx=canvas.getContext("2d");
         canvas.addEventListener("mousedown", relMouseCoords, false);

        var img=new Image();
            img.onload = function() {
                ctx.drawImage(img, 0, 0,canvas.width,canvas.height);
            }
            img.src = "data:image/jpeg;base64,"+ theSection.picture;

        img.addEventListener('load', function() { 
            if(theSection.allHotSpots.length > 0) {
                for( var x = 0; x < theSection.allHotSpots.length; x++) {
                    appendHotSpot(theSection.allHotSpots[x], theSection.thePicture, ctx);
                }
            }

        }, false);

    }
    appendSectionQuestions(theSection, list);
    if (theSection.allSubSections) {
        for (var x = 0; x < theSection.allSubSections.length; x++) {
            var theSectionA = theSection.allSubSections[x];
            appendSection(theSectionA, list);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是appendPicture,它创建画布html并将其附加到元素.

function appendPicture(list, theSection) {

        list.append('<div id="wrapper' + platform + '" style="width:100%; text-align:center">\
            <canvas class="assessmentImageSmall" style="width:100%;height:' + Math.round(theSection.thePicture.ySize * (document.getElementById('assessmentSectionForm' + platform).clientWidth / theSection.thePicture.xSize)) + 'px" id="assessmentImage' + platform + '" align="middle" ></canvas>\
            <!--<p style="color:#666;" id="imageInstruction">Tap image to enlarge.</p>-->\
            </div>');
        $("#wrapper").kendoTouch({
                                     tap: function (e) {
                                         switchImage();
                                     }
                                 });
}
Run Code Online (Sandbox Code Playgroud)

这是我画矩形的地方(我在这个函数中调用矩形热点)

function appendHotSpot(HotSpot, picture, ctx) {
    var imageWidth = document.getElementById('assessmentImage' + platform).clientWidth;

    var scale = imageWidth / picture.xSize;

    HotSpot.topLeft = [Math.round(HotSpot.topLeft[0] * scale), Math.round(HotSpot.topLeft[1] * scale)];
    HotSpot.bottomRight = [Math.round(HotSpot.bottomRight[0] * scale), Math.round(HotSpot.bottomRight[1] * scale)];

    var rect = {x1: HotSpot.topLeft[0], y1: HotSpot.topLeft[1], x2: HotSpot.bottomRight[0], y2: HotSpot.bottomRight[1]};

    ctx.strokeStyle="red";
    ctx.beginPath();
    ctx.moveTo(rect.x1, rect.y1);
    ctx.lineTo(rect.x2, rect.y1);
    ctx.lineTo(rect.x2, rect.y2);
    ctx.lineTo(rect.x1, rect.y2);
    ctx.lineTo(rect.x1, rect.y1);
    ctx.stroke();
}
Run Code Online (Sandbox Code Playgroud)

Sho*_*omz 10

画布的宽度和高度与CSS的宽度和高度不同!

这意味着画布会拉伸以与CSS大小对齐.这适用于缩放,但可能会导致像宽度那样的问题:100%.


两种解决方案(取决于您的需求):

  • 读取画布的DOM元素大小并将其应用于画布本身(请参阅下面示例中的第4个画布)
  • 根据画布的实际大小修改其CSS样式(参见下面的第5幅画布)

简单的例子:

function buildCanvas(w, h, sizeFromDOM, changeCSS, looksFine) {
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  document.body.appendChild(canvas);
  canvas.style.borderColor = looksFine ? "green" : "red";

  if (sizeFromDOM) {
    // read its size from the DOM
    canvas.width = canvas.offsetWidth;
    canvas.height = canvas.offsetHeight;
  } else {
    // or simply apply what was given
    canvas.width = w;
    canvas.height = h;
  }
  
  // change CSS styles if needed
  if (changeCSS) {
    canvas.style.width = canvas.width + 'px';
    canvas.style.height = canvas.height + 'px';
  }
  
  // draw the same 80x80 square on each
  ctx.strokeStyle = looksFine ? "green" : "red";
  ctx.beginPath();
  ctx.moveTo(10, 10);
  ctx.lineTo(90, 10);
  ctx.lineTo(90, 90);
  ctx.lineTo(10, 90);
  ctx.lineTo(10, 10);
  ctx.stroke();
}

buildCanvas(200, 200, false, false, true); // this canvas is fine as it matches the CSS sizes
buildCanvas(300, 200); // this canvas is stretched horizontally
buildCanvas(200, 300); // this canvas is stretched vertically
buildCanvas(200, 300, true, false, true); // let's fix this one
buildCanvas(300, 200, false, true, true); // this one too, but by changing its CSS
Run Code Online (Sandbox Code Playgroud)
canvas {
  width: 200px;
  height: 200px;
  border: 1px solid #aaa;
  margin: 4px;
}
Run Code Online (Sandbox Code Playgroud)