LoginSignup
2
1

More than 5 years have passed since last update.

JavaScript:HTML5 Canvas

Last updated at Posted at 2018-06-24

始めに

オーライリージャパンの「HTML5 Canvas」に掲載されているサンプルコードを改造してみました

背景

本書の趣旨としておそらく、JavaScriptの初心者が読むことを考慮しているのかサンプルコードはCanvasをFunctionの一つのローカル変数として扱っている
Canvasタグの解説としては本書のような関数にCanvasオブジェクトを閉じ込めてしまってもいいが、実務では動的にDiv+Canvasを扱いたくなる場合もあるかもしれない
なので、サンプルプログラムをオブジェクト指向風に改造して、動的にDiv+Canvasを生成できるようにした

ソースの解説

  • CanvasのオブジェクトとCanvasに対する操作は一つのFunctionオブジェクトにまとめています
  • テキストボックスに入れた数値が動的に作られるDiv+Canvasの座標になります。Divはpostionをrelativeに指定しているので、divの座標は最後に追加されたDivが基準になります。
  • 本来、この手のアプリはReactあたりを使ったほうがDomのわずらわしさから解放されるからいいと思うのだけど、今回はそこまでするのも面倒くさいので、パスしています

ソース

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ch1Ex3: Your First Canvas Application </title>
<script src="modernizr-2.0.6.js"></script>
<script>

var canvasCnt=0;
//動的にCanvas付きのDivを生成する
function appendcanvas(divId,divAttributes){
    var parentDiv = document.getElementById("parentDiv")
    var childDiv = document.createElement("div");
    var divId=divId+canvasCnt
    var canvasId="appendedcanvas"+canvasCnt;

    childDiv.setAttribute("id",divId)
    childDiv.style.borderStyle="solid"
    childDiv.style.width="100px"
    childDiv.style.height="120px"
    childDiv.style.position="relative"
    childDiv.style.top=divAttributes[0]
    childDiv.style.left=divAttributes[1]
    parentDiv.appendChild(childDiv)

    var appendedcanvas = document.createElement("canvas");
    appendedcanvas.setAttribute("id",canvasId)
    childDiv.appendChild(appendedcanvas)

    var canvasObj = new CanvasObject ();
    if(!canvasObj.init("appendedcanvas"+canvasCnt)){
        return;
    }
    canvasObj.setBackground("#ffaaaa",[0, 0, 100, 120])
    canvasObj.setText("#000000","20px _sans","top",["added", 10, 20])
    //canvasObj.drawBox("#000000",[5, 5, 490, 290])
    canvasCnt++;
}


window.addEventListener("load", eventWindowLoaded, false);
var Debugger = function () { };
Debugger.log = function (message) {
    try {
        console.log(message);
    } catch (exception) {
        return;
    }
}

function eventWindowLoaded () {
    drawScreen();
}

function canvasSupport () {
    return Modernizr.canvas;
}
function drawScreen() {
    var canvasObj = new CanvasObject ();
    if(!canvasObj.init("canvasOne")){
        return;
    }
    canvasObj.setBackground("#ffffaa",[0, 0, 500, 300])
    canvasObj.setText("#000000","20px _sans","top",["Hello World!", 195, 80])
    canvasObj.drawImage("helloworld.gif",[160, 130])
    canvasObj.drawBox("#000000",[5, 5, 490, 290])
}


function CanvasObject () {
    var theCanvas;
    var context; 
    //canvasの初期化
    this.init = function(canvasId){
        if (!canvasSupport()) {
            return false;
        }
        theCanvas = document.getElementById(canvasId);//"canvasOne"
        context = theCanvas.getContext("2d"); 
        Debugger.log("Drawing Canvas");
        return true;
    }

    //canvasの背景を設定する(四角形を描画し、内部を塗りつぶす)
    this.setBackground=function(fillStyle,fillRect){
        context.fillStyle = fillStyle;//"#ffffaa";
        context.fillRect(fillRect[0],fillRect[1],fillRect[2],fillRect[3]); //0, 0, 500, 300
    }

    //文字列を描画する
    this.setText =function(fillStyle,font,textBaseline,textAttribute){
        context.fillStyle    = fillStyle;
        context.font         = font ;
        context.textBaseline = textBaseline;
        context.fillText(textAttribute[0],textAttribute[1],textAttribute[2] );//"Hello World!", 195, 80
    }

    //イメージを設定する
    this.drawImage=function(imageSrc,position){
        //image
        var helloWorldImage = new Image();
        helloWorldImage.onload = function () {
            context.drawImage(helloWorldImage,position[0],position[1]);/
        }
        helloWorldImage.src = imageSrc//"helloworld.gif";
    }
    //canvasの枠をつける
    this.drawBox=function(strokeStyle,strokeRect){
        context.strokeStyle = strokeStyle//"#000000";
        context.strokeRect(strokeRect[0],strokeRect[1],strokeRect[2],strokeRect[3]);
    }
}


</script> 
</head>
<body>
<div style="position:relative;top:10px;">
    <input type=text id='xaxis'>
    <input type=text id='yaxis'>
    <input type="button" value="キャンバス追加" 
    onclick="appendcanvas('mydiv',[document.getElementById('xaxis').value+'px',document.getElementById('yaxis').value+'px'])">
</div>
<div style="position: absolute; top: 50px; left: 50px;width:1200px;height:700px;border-style:solid;border-color: red;" id="parentDiv">
    <div style="position:relative;top: 50px; left: 50px;border-style:solid;width:500px; height:300px">
        <canvas id="canvasOne" width="500" height="300">
        Your browser does not support HTML 5 Canvas.
        </canvas>
    </div>
</div>
</body>
</html>
2
1
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
2
1