LoginSignup
1
0

More than 5 years have passed since last update.

canvasを画面比に応じて可変にする(canvasでお絵かきアプリ)

Last updated at Posted at 2018-05-26

背景

canvasを画面サイズに応じて可変させたい。
純粋にそのまま実行するとjavascriptにて操作するときにcssで書いた値は有効にならず、「幅300px 高さ150px」という認識で動くのです…

結論

回避策としては下記…


window.onresize =//<- resize時も対応
window.onload  = function() {
var cnv=document.getElementsByClassName('cnv')[0];
var ctx=cnv.getContext('2d');
cnv.setAttribute('width',cnv.clientWidth);  //<- sizeを教えてあげる
cnv.setAttribute('height',cnv.clientHeight);//<- sizeを教えてあげる

var p=false;
cnv.addEventListener('mousemove', (e)=>{
  console.log(e.which,cnv);
  if(e.which==1){
    if(!p){
      ctx.beginPath();
      ctx.strokeStyle="#fff";
      ctx.moveTo(e.x, e.y);
      p=true;
    }else{
      ctx.lineTo(e.x, e.y);
      ctx.stroke();
    }
  }else{
    p=false;
  }
});
};

属性として書き込んであればそれをもとに動くようです。

追加

表記の機能を利用して簡単なお絵描きキャンバスを実装したので、ここに共有させていただきます…
消しゴム・色選択・ペンサイズ変更は実装済みです。

See the Pen canvas by hashito (@hashito) on CodePen.

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0