javascript - HTML Canvas 和正确显示的小问题?

标签 javascript html css canvas

我正在尝试调整大小以正确地将其放置在中间和更大的 div 中。我希望它是 500x500。我想做的是制作 Windows Paint 的经典版本。

问题是将“ Canvas ”调整到中间会阻止画笔“绘制”。

这是我到目前为止的代码。

<!DOCTYPE HTML>
<html>
  <head>
    <style>

    body {
    width: 500px;
    height: 500px;
    margin: auto;
    top: 50%; 
    left: 50%;
    width: 90%;
    border: 3px solid #73AD21;
    padding: 10px;

      }

    </style>
  </head>
  <body>
    <div id="paint" >
        <canvas id="myCanvas"></canvas>
    </div>
    <script>


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

var painting = document.getElementById('paint');
var paint_style = getComputedStyle(painting);
canvas.width = parseInt(paint_style.getPropertyValue('width'));
canvas.height = parseInt(paint_style.getPropertyValue('height'));

var mouse = {x: 0, y: 0};

canvas.addEventListener('mousemove', function(e) {
  mouse.x = e.pageX - this.offsetLeft;
  mouse.y = e.pageY - this.offsetTop;
}, false);

ctx.lineWidth = 10;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = '#00CC99';

canvas.addEventListener('mousedown', function(e) {
    ctx.beginPath();
    ctx.moveTo(mouse.x, mouse.y);

canvas.addEventListener('mousemove', onPaint, false);
}, false);

canvas.addEventListener('mouseup', function() {
    canvas.removeEventListener('mousemove', onPaint, false);
}, false);

var onPaint = function() {
    ctx.lineTo(mouse.x, mouse.y);
    ctx.stroke();
};

    </script>
  </body>
</html>      

最佳答案

去掉body上的样式并将其替换为:

#paint {
  height: 500px;
  margin: auto;
  width: 90%; /* you also had width: 500px, which one did you want? */
  border: 3px solid #73AD21;
  padding: 10px;
}

Fiddle - 看起来这个改变工作正常。

关于javascript - HTML Canvas 和正确显示的小问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36242833/

相关文章:

javascript - 自定义指令内的条件 ngClass

javascript - 向数组原型(prototype)添加一个函数

javascript - 在浏览器中调整图像大小

javascript - 使用 jquery 联系表单验证错误

jquery - 文本区域与粘性页脚重叠

javascript - 随机幻灯片仅在超过两张幻灯片时才有效

javascript - Facebook JavaScript API : '/me/albums' not working for other users

Jquery 在 json 提要上查找替换文本

JavaScript 选择

html - 使用嵌套的 HTML 表单,是否可以定位提交时传输的内容?