HTML5 canvas patterns - javascript

I wrote the following code on my text editor:
!DOCTYPE html><html><head><script>
window.onload = function()
{
canvas = document.getElementById("canvasArea");
context = canvas.getContext("2d");
var smallIMage = new Image();
smallImage.src = "https://vignette.wikia.nocookie.net/cardfight/images/8/89/De.jpg/revision/latest?cb=20130414214050";
smallImage.onload = function()
{
context.shadowOffsetX = 4;
context.shadowOffsetY = 4;
context.shadowBlur = 20;
context.shadowColor = "lavender";
context.strokestyle = "gray";
context.lineWidth = 1;
var repeatPattern = context.createPattern(smallImage, "repeat");
var noRepeatPattern = context.createPattern(smallImage, "no-repeat");
var repeatXPattern = context.createPattern(smallImage, "repeat-x");
var repeatYPattern = context.createPattern(smallImage, "repeat-y");
context.fillStyle = repeatPattern;
context.fillRect (125, 125, 325, 325);
context.strokeRect (125, 125, 325, 325);
context.fillStyle = noRepeatPattern;
context.fillRect (0, 0, 100, 100);
context.strokeRect (0, 0, 100, 100);
context.fillStyle = repeatXPattern;
context.fillRect (125, 0, 350, 100);
context.strokeRect (125, 0, 350, 100);
context.fillStyle = repeatYPattern;
context.fillRect (0, 125, 100, 350);
context.strokeRect (0, 125, 100, 350);
}
}
</script></head><body>
<div style = "width:500px; height:500px;
margin:0 auto; padding:5px;">
<canvas id = "canvasArea"
width = "500" height = "500"
style = "border:2px solid black">
Your browser doesn't currently support HTML5 canvas.
</canvas>
</div>
</body>
</html>
This code s supposed to create a pattern from an online image, but it's not showing as the canvas is completely blank. Can you please tell me what I did wrong.

There wasn't much wrong with your code apart from correcting a few spelling inconsistencies and defining the new Image() event handler before assigning it's .src property. Also, remember to declare the charset of the document in the head section of the file. E.G...
<head>
<meta charset="utf-8">
... etc ...
</head>
Anyway, after a little editing the major components of your page look like this.
document.addEventListener('DOMContentLoaded', function() {
var canvas = document.getElementById("canvasArea"),
ctx = canvas.getContext("2d"),
smallImage = new Image();
/* set canvas dimensions */
canvas.width = canvas.height = 500;
smallImage.addEventListener("load", function() {
/* the image is bound to the
function's 'this' property */
var repeatPattern = ctx.createPattern(this, "repeat"),
noRepeatPattern = ctx.createPattern(this, "no-repeat"),
repeatXPattern = ctx.createPattern(this, "repeat-x"),
repeatYPattern = ctx.createPattern(this, "repeat-y");
ctx.shadowOffsetX = 4;
ctx.shadowOffsetY = 4;
ctx.shadowBlur = 20;
ctx.shadowColor = "rgb(230,230,250)";
ctx.strokestyle = "rgb(128,128,128)";
ctx.lineWidth = 1;
ctx.fillStyle = repeatPattern;
ctx.fillRect (125, 125, 325, 325);
ctx.strokeRect (125, 125, 325, 325);
ctx.fillStyle = noRepeatPattern;
ctx.fillRect (0, 0, 100, 100);
ctx.strokeRect (0, 0, 100, 100);
ctx.fillStyle = repeatXPattern;
ctx.fillRect (125, 0, 350, 100);
ctx.strokeRect (125, 0, 350, 100);
ctx.fillStyle = repeatYPattern;
ctx.fillRect (0, 125, 100, 350);
ctx.strokeRect (0, 125, 100, 350);
}, !1);
/* define Image.onload event handler
before assigning Image.src */
smallImage.src = "https://vignette.wikia.nocookie.net/cardfight/images/8/89/De.jpg/revision/latest?cb=20130414214050";
}, !1);
body {
background:rgb(90,90,110);
padding:33px 0 }
#box {
width:500px;
height:500px;
background:rgb(50,50,70);
margin:0 auto;
box-shadow:0 0 0.25em 0.5em rgba(0,0,0,0.25) }
#canvasArea {
width:100%;
height:100%;
border:2px solid rgb(22,22,22) }
<div id="box">
<canvas id="canvasArea">
Your browser doesn't currently support HTML5 canvas.
</canvas>
</div>
BP ;)

Related

I'm trying to display shapes using canvas and they aren't showing up

I am working on a simple game (following a tutorial on Zenva Academy) and, although I've followed the instructions to a T, I can't seem to get my canvas shapes to show up in the browser. Here is the code I have so far:
var canvas = document.getElementByID('myCanvas');
var ctx = canvas.getContext('2d');
let screenWidth = 1000;
let screenHeight = 500;
class GameCharacter {
constructor(x, y, width, height, color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
}
}
var blueSquare = new GameCharacter(
50, 50, 50, 50, "rgb(0, 0, 255)"
);
var rectangle = new GameCharacter(
75, 75, 100, 50, "rgb(0, 255, 0)"
);
var redSquare = new GameCharacter(
100, 50, 50, 50, "rgb(255, 0, 0)"
);
var draw = function() {
ctx.clearRect(0, 0, screenWidth, screenHeight);
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.fillRect(blueSquare.x, blueSquare.y, blueSquare.width, blueSquare.height);
ctx.fillStyle = rectangle.color;
ctx.fillRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
ctx.fillStyle = redSquare.color;
ctx.fillRect(redSquare.x, redSquare.y, redSquare.width, redSquare.height);
}
var step = function() {
draw();
window.requestAnimationFrame(step);
}
canvas {
border: 4px solid green;
background-color: yellow;
}
<canvas id='myCanvas' width='1000' height='500'></canvas>
I am still fairly new to this and this is the first question I've ever asked on a forum. Let me know if I'm doing something wrong. LOL!
I am using:
OS: Windows 10 Pro 64-bit
Browser: Tried both Chrome and Microsoft Edge
Code Editor: Sublime Text 3
A simple typo - you have written getElementByID, while you should have getElementById. (This shows up immediately in your browser's developer tools' console.)
Then, you'll need to call step() once to kick things off.
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
let screenWidth = 1000;
let screenHeight = 500;
class GameCharacter {
constructor(x, y, width, height, color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
}
}
var blueSquare = new GameCharacter(
50, 50, 50, 50, "rgb(0, 0, 255)"
);
var rectangle = new GameCharacter(
75, 75, 100, 50, "rgb(0, 255, 0)"
);
var redSquare = new GameCharacter(
100, 50, 50, 50, "rgb(255, 0, 0)"
);
var draw = function() {
ctx.clearRect(0, 0, screenWidth, screenHeight);
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.fillRect(blueSquare.x, blueSquare.y, blueSquare.width, blueSquare.height);
ctx.fillStyle = rectangle.color;
ctx.fillRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
ctx.fillStyle = redSquare.color;
ctx.fillRect(redSquare.x, redSquare.y, redSquare.width, redSquare.height);
}
var step = function() {
draw();
window.requestAnimationFrame(step);
}
step();
canvas {
border: 4px solid green;
background-color: yellow;
}
<canvas id='myCanvas' width='1000' height='500'></canvas>

Canvas Javascript draw function not working

I am trying to separate canvas context from the actual draw functions but not working. As part of the context I wish to include the ability to resize the canvas which isn't working. The HTML works fine as this is evident with the getElementbyID working. The draw function which works fine is included for reference.
window.onload = function() {
'use strict';
var ctx = getCanvas();
draw(ctx);
}
function getCanvas() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var w = canvas.width = 200;
var h = canvas.height = 150;
return ctx;
}
function draw(ctx) {
ctx.fillStyle = 'rgb(200, 0, 0)';
ctx.fillRect(10, 10, 50, 50);
ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
ctx.fillRect(30, 30, 50, 50);
}
I see no issues with your code. It works as expected.
window.onload = function() {
'use strict';
var ctx = getCanvas();
draw(ctx);
};
function getCanvas() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var w = canvas.width = 200;
var h = canvas.height = 150;
return ctx;
}
function draw(ctx) {
ctx.fillStyle = 'rgb(200, 0, 0)';
ctx.fillRect(10, 10, 50, 50);
ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
ctx.fillRect(30, 30, 50, 50);
}
canvas{border: 1px solid black}
<canvas id="canvas" width="1000" height="1000"></canvas>
note: do not set canvas­'s width and height using css (in first place).

How add image to canvas by layers?

This is my code:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(55, 95, 30, 0, 2 * Math.PI);
var ctx1 = c.getContext("2d");
ctx1.rect(0, 0, 200, 300);
ctx.clip();
ctx.stroke();
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d');
make_base();
function make_base() {
base_image = new Image();
base_image.src = 'https://www.gravatar.com/avatar/4af2cdbaf02d97ba88d5d6daff94fbae/default=&s=80';
base_image.onload = function() {
context.drawImage(base_image, 15, 55);
}
}
canvas {
border: 1px solid #000000;
position: absolute;
top: 66px;
left: 22px;
}
<canvas id="myCanvas" width="236" height="413"></canvas>
From my code above I try to add image in to the circle and rectangle
I have done with add image in circle I try to add one more image in to the rectangle for the background but it seem not works.
You just need to create a second image and position it accordingly. Also use only one context, there is no need to declare it multiple times. Modified your code. I hope this will help you:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(55, 95, 30, 0, 2 * Math.PI);
ctx.rect(18, 150, 200, 250);
ctx.clip();
ctx.stroke();
make_base();
function make_base() {
base_image = new Image();
base_image.src = 'https://www.gravatar.com/avatar/4af2cdbaf02d97ba88d5d6daff94fbae/?default=&s=80';
base_image.onload = function() {
ctx.drawImage(base_image, 15, 55);
}
second_image = new Image();
second_image.src = 'https://www.gravatar.com/avatar/4af2cdbaf02d97ba88d5d6daff94fbae/?default=&s=80';
second_image.onload = function() {
ctx.drawImage(second_image, 19, 151);
}
}
<canvas id="myCanvas" width="236" height="413" style="border:1px solid #000000; position:absolute; top:66px; left:22px;"></canvas>

Why isn't my drawing showing on canvas?

I drew various shapes and text on my canvas, but nothing is showing in the browser. There are no errors in Chrome's console. I opened it in another browser, thinking it may have been a problem with cache, but still nothing except the "Draw Canvas" button shows. Here it is in jsfiddle: https://jsfiddle.net/0Lakv2do/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#content-wrapper {
width: 600px;
margin: 0 auto;
text-align: center;
}
#canvasRun {
background-color: #c00;
border: 0;
color: #fff;
}
</style>
</head>
<body>
<div id="content-wrapper">
<button id="canvasRun">Draw Canvas</button><br><br>
<canvas id="myCanvas" width="600" height="450"></canvas>
</div>
<script type="text/javascript">
var contentWrapper = document.getElementById('contentWrapper');
var runButton = document.getElementById('canvasRun');
var canvas = document.getElementById('myCanvas');
myCanvas.style.visibility="hidden";
runButton.addEventListener('click', showCanvas, false);
function showCanvas() {
myCanvas.style.visibility = "visible";
if (myCanvas.getContext){
var logo = new Image();
logo.src = 'IIT_SAT_stack_186_white.png';
function renderMyCanvas() {
var ctx = canvas.getContext('2d');
var linearGrad = ctx.createLinearGradient(0,0,0,450);
linearGrad.addColorStop(0, 'white');
linearGrad.addColorStop(1, 'black');
ctx.fillStyle=linearGrad;
ctx.fillRect(0,20,600,450);
ctx.font = "32px sans-serif";
ctx.fillStyle = 'red';
ctx.fillText("ITMD 565 Canvas Lab", 135, 75);
ctx.beginPath();
ctx.moveTo(15, 90);
ctx.lineTo(580, 90);
ctx.lineWidth = 3;
ctx.strokeStyle = 'red';
ctx.closePath();
ctx.stroke();
ctx.font = "14px sans-serif";
ctx.fillStyle = 'white';
ctx.fillText("", 15, 410);
ctx.fillText("", 15, 430);
ctx.drawImage(logo, 300, 360, 250, 60);
ctx.fillStyle= 'white';
ctx.fillRect(250, 250, 310, 100);
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
var startAngle = 1.1 * Math.PI;
var endAngle = 1.9 * Math.PI;
var counterClockwise = false;
ctx.beginPath();
ctx.arc(x, y, radius, startAngle, endAngle, counterClockwise);
ctx.lineWidth = 15;
ctx.arc.strokeStyle = 'yellow';
ctx.stroke();
ctx.setLineDash([10, 10]);
ctx.beginPath();
ctx.moveTo(270,300);
ctx.quadraticCurveTo(330, 220, 395, 300, 395, 300);
ctx.strokeStyle = 'black';
ctx.stroke();
ctx.beginPath();
ctx.moveTo(395, 300);
ctx.quadraticCurveTo(450, 375, 540, 300);
ctx.strokeStyle = 'black';
ctx.stroke();
}
}
}
</script>
</body>
</html>
You have just copy/pasted a function inside your other function and you don't ever call it. You also have a different variable canvas there while in the outer one you have myCanvas.
When copy/pasting make sure you actually know what you are copying and how it works.
See a Fiddle with the function definition removed and the variable name fixed.

Failed to manipulate image with zoom button

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<style>
body {
margin: 0px;
padding: 0px;
}
#wrapper {
position: relative;
border: 1px solid #9C9898;
width: 578px;
height: 200px;
}
#buttonWrapper {
position: absolute;
width: 30px;
top: 2px;
right: 2px;
}
input[type =
"button"] {
padding: 5px;
width: 30px;
margin: 0px 0px 2px 0px;
}
</style>
<script>
function draw(scale, translatePos){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 69, 50);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
// clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
context.save();
context.translate(translatePos.x, translatePos.y);
context.scale(scale, scale);
/*context.beginPath(); // begin custom shape
context.moveTo(-119, -20);
context.bezierCurveTo(-159, 0, -159, 50, -59, 50);
context.bezierCurveTo(-39, 80, 31, 80, 51, 50);
context.bezierCurveTo(131, 50, 131, 20, 101, 0);
context.bezierCurveTo(141, -60, 81, -70, 51, -50);
context.bezierCurveTo(31, -95, -39, -80, -39, -50);
context.bezierCurveTo(-89, -95, -139, -80, -119, -20);
context.closePath(); // complete custom shape
var grd = context.createLinearGradient(-59, -100, 81, 100);
grd.addColorStop(0, "#8ED6FF"); // light blue
grd.addColorStop(1, "#004CB3"); // dark blue
context.fillStyle = grd;
context.fill();
context.lineWidth = 5;
context.strokeStyle = "#0000ff";
context.stroke();*/
context.restore();
}
window.onload = function(){
var canvas = document.getElementById("myCanvas");
var translatePos = {
x: canvas.width / 2,
y: canvas.height / 2
};
var scale = 1.0;
var scaleMultiplier = 0.8;
var startDragOffset = {};
var mouseDown = false;
// add button event listeners
document.getElementById("plus").addEventListener("click", function(){
scale /= scaleMultiplier;
draw(scale, translatePos);
}, false);
document.getElementById("minus").addEventListener("click", function(){
scale *= scaleMultiplier;
draw(scale, translatePos);
}, false);
// add event listeners to handle screen drag
canvas.addEventListener("mousedown", function(evt){
mouseDown = true;
startDragOffset.x = evt.clientX - translatePos.x;
startDragOffset.y = evt.clientY - translatePos.y;
});
canvas.addEventListener("mouseup", function(evt){
mouseDown = false;
});
canvas.addEventListener("mouseover", function(evt){
mouseDown = false;
});
canvas.addEventListener("mouseout", function(evt){
mouseDown = false;
});
canvas.addEventListener("mousemove", function(evt){
if (mouseDown) {
translatePos.x = evt.clientX - startDragOffset.x;
translatePos.y = evt.clientY - startDragOffset.y;
draw(scale, translatePos);
}
});
draw(scale, translatePos);
};
jQuery(document).ready(function(){
$("#wrapper").mouseover(function(e){
$('#status').html(e.pageX +', '+ e.pageY);
});
})
</script>
</head>
<body onmousedown="return false;">
<div id="wrapper">
<canvas id="myCanvas" width="578" height="200">
</canvas>
<div id="buttonWrapper">
<input type="button" id="plus" value="+"><input type="button" id="minus" value="-">
</div>
</div>
<h2 id="status">
0, 0
</h2>
</body>
</html>
The above code taken from this question, which works perfectly fine by simply copying all the code. My objective is to keep everything remaining the same but using an image instead of cloud shape that drew by context. I tried drawImage method and successfully draw the image but I couldn't zoom in/out or even drag anymore. May I know what's wrong with context?
Ok, what happens in your code now is that you draw your image after the restore call has been called resulting in that nothing happens.
This is because the image loading is asynchronous.
What you need to do is to integrate the image loading so that it finishes earlier in the pipe-line, then use the image integrated in the scaling, for example by taking the image loading out of the draw function:
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function() {
/// now the image has loaded, now we can scale it
draw();
};
imageObj.src = 'image-url';
function draw() {
// clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
context.save();
context.translate(translatePos.x, translatePos.y);
context.scale(scale, scale);
/// draw image here
context.drawImage(imageObj, 69, 50);
context.restore();
}
Then for each time you need to re-scale the image just call draw().
ONLINE DEMO HERE

Categories

Resources