I found a really nice Minesweeper online game (link) and decided to understand a little bit better Canvas and JavaScript relations. One thing that I'm finding interesting is the resizable option this game has. If you click and drag at the bottom right corner of the puzzle, you can resize it. So I decided to investigate its source code to learn more and I learned this:
How to add the canvas to the HTML body and how to link it to a JavaScript file:
<div align="center">
<div id="divResizable", style="position: relative; left: 0px; top: 0px; width: 1000px;">
<canvas id="myCanvas", style="display:block; border:1px solid #000000;", width = "1000", height = "400">
HTML5 needed for Canvas to appear
</canvas>
</div>
</div>
<script type="text/javascript" src="expandCanvas.js"></script>
How to add the click and drag icon to this canvas with JavaScript:
// Creates icon
var resize_handle = document.createElement("canvas");
resize_handle.width = 10;
resize_handle.height = 10;
{
var ctx = resize_handle.getContext("2d");
ctx.beginPath();
for (var i = 1; i <= 7; i += 3) {
ctx.moveTo(8.5, i + 0.5);
ctx.lineTo(i + 0.5, 8.5);
}
ctx.lineWidth = '1px';
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.strokeStyle = '#000000';
ctx.stroke();
}
// Append icon to div "divResizable"
resizable_div = document.getElementById("divResizable");
resizable_div.appendChild(resize_handle);
resize_handle.style.position = 'absolute';
resize_handle.style.zIndex = 100; // The greater this value, more forward the icon gets ("z coordinate")
resize_handle.style.bottom = "0";
resize_handle.style.right = "0";
resize_handle.style.cursor = "se-resize"; // Changes cursor style
resize_handle.title = "Click and Drag to resize this canvas";
Well, after that they combined a compiled C function (using Module.cwrap()
) with some mouse event listener to handle the resize procedure. (link to their Java Script, starts at line 411). From now on I'm struggling to understand. Even though they use a compiled C function, I believe that HTML/JavaScript might have a simpler solution for that. Doesn't it?
In this puzzle that I'm using as an example, when resizing, it keeps its proportions. I believe that's why it get sophisticated. For me, I'm just curious to learn Canvas and JavaScript. So a simpler solution that just resize the canvas based on the mouse position without the need of keeping its proportions is good enough for me.
What would be a simpler and more standard way of doing that with JavaScript/Canvas?