Hi i'm having trouble getting my paint canvas buttons that change the colours of the paint brush to move beside the canvas.
It seems to be stuck at the tope left hand corner of the webpage unfortunately and i'm struggling trying to re-locate it. And suggestions would be very helpful. Thank you.
Here is some of my code that should give you an idea of what im talking about.
var brush = 10;
function changeColour(colour)
{
g.fillStyle = colour;
}
function clearCanvas()
{
g.clearRect(0, 0, canvas.width, canvas.height);
}
var mouseIsDown = false;
function down(e)
{
mouseIsDown = true;
/*e.originalEvent.preventDefault();*/
}
function up(e)
{
mouseIsDown = false;
}
function changeBrushSize(symbol)
{
if(symbol =='+')
{
brush = brush + 2;
}
else if (symbol == '-')
{
brush = brush - 2;
}
}
function move(e)
{
var container = document.getElementById('container');
//g.clearRect(0, 0, canvas.width, canvas.height);
//g.fillRect(e.x - 5, e.y - 5, 100, 100);
if((e.button == 0) && (mouseIsDown))
{
g.beginPath();
document.onselectstart = function(){ return false; }
//g.fillStyle = "red";
g.arc((e.x - container.offsetLeft) - brush, (e.y - container.offsetTop) - brush, brush, 0, Math.PI * 2);
g.fill();
g.closePath();
}
}
</script>
</head>
<body>
<div id="container">
<canvas id = "paintCanvas" width = "500" height = "500">
Your browser does not support the HTML5 <canvas> tag.
</canvas>
</div>
<button onclick ="clearCanvas()">Clear Canvas</button></br>
<button onclick ="changeColour('red')">Red</button>
<button onclick ="changeColour('green')">Green</button>
<button onclick ="changeColour('blue')">Blue</button>
<button onclick ="changeColour('yellow')">Yellow</button>
<button onclick ="changeColour('orange')">Orange</button>
<button onclick ="changeColour('brown')">Brown</button>
<button onclick ="changeColour('purple')">Purple</button></br>
<button onclick ="changeBrushSize('+')">Bigger Brush</button>
<button onclick ="changeBrushSize('-')">Smaller Brush</button>
</body>
You might let the user select their colors and other tools from a second "tools" canvas
Then position the "tools" canvas before the "drawing" canvas.
<canvas id="toolsCanvas"></canvas><br>
<canvas id="drawingCanvas"></canvas>
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/y5xu7/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: white; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("drawingCanvas");
var context=canvas.getContext("2d");
var tools=document.getElementById("toolsCanvas");
var ctx=tools.getContext("2d");
var canvasOffset=$("#toolsCanvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var colors=['Red','Green','Blue','Yellow','Orange','Brown','Purple']
var lightcolors="Yellow|White";
var colorPickerWidth=25;
// draw the color picker
tools.width=colors.length*colorPickerWidth;
for(var i=0;i<colors.length;i++){
ctx.fillStyle=colors[i];
ctx.fillRect(i*colorPickerWidth,0,colorPickerWidth,25);
}
// called when the user clicks and picks a color
function handleMouseDown(e){
console.log("down");
var x=parseInt(e.clientX-offsetX);
var color=colors[parseInt(x/colorPickerWidth)];
ctx.save();
ctx.fillStyle=color;
ctx.fillRect(0,28,tools.width,25);
ctx.fillStyle="white";
if(lightcolors.indexOf(color)>-1){ctx.fillStyle="black";}
ctx.font="16px verdana";
ctx.fillText("Selected: "+color,10,45);
ctx.restore();
context.clearRect(0,0,canvas.width,canvas.height);
context.fillStyle=color;
context.font="14px arial";
context.fillText("fillStyle==your selected color",30,100);
}
$("#toolsCanvas").mousedown(function(e){handleMouseDown(e);});
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="toolsCanvas" width=300 height=53></canvas><br>
<canvas id="drawingCanvas" width=300 height=300></canvas>
</body>
</html>
Related
I am having trouble creating game on html canvas. The premise of the game is you have to catch the balloons before they hit the ground. I am having problems with the background of the canvas and the basket is not moving with the mouse.
The background should be black and the basket should be following the mouse curser.
https://jsfiddle.net/pgkL09j7/8/
<html>
<head>
<title>Sean Coyne</title>
<link rel="stylesheet" type="text/css" href="home.css">
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body onload="start_game()">
<body>
<section>
<article>
<div id="logo"><img src="LogoComic.png" id="Logo"></div><br></br>
<div id="canvas">
<canvas id="c" style="border:5px solid orange" height="500" width="500"></canvas>
<p id="p1"></p>
<script>
var balloon_x=100;
var balloon_y=0;
var basket_x=100;
var basket_y=100;
var points=0;
//Background colour of canvas
var c = document.getElementById("c");
var ctx = c.getContext("2d");
ctx.fillStyle = "#000";
ctx.fillRect(0,0,500,500);
//Here is the event listener
mycanv.addEventListener("mousemove",seenmotion, false);
function seenmotion(e) {
//This is the code for the mouse
//moving over the canvas.
var bounding_box=c.getBoundingClientRect();
basket_x=(e.clientX-bounding_box.left) *
(c.width/bounding_box.width);
basket_y=(e.clientY-bounding_box.top) *
(c.height/bounding_box.height);
}
function start_game() {
setInterval(game_loop, 50);
}
function game_loop() {
// The code above is called every 50ms and is a
// frame-redraw-game-animation loop.
c.width = c.width;
// Below is the code that draws the objects
draw_balloon(balloon_x,balloon_y);
draw_basket(basket_x,basket_y);
// Below is the code that updates the balloons location
balloon_x++;
if (balloon_x>c.width) {
balloon_x=0;
}
//Here is the collision detection code
if (collision(balloon_x, balloon_y, basket_x, basket_y)) {
points -= 0.5;
}
//Here is the code for the point system
points+=1;
// and let's stick it in the top right.
var integerpoints=Math.floor(points); // make it into an integer
ctx.font="bold 24px sans-serif ";
ctx.fillText(integerpoints, c.width-50, 50);
}
context.clearRect ( 0 , 0 , 500, 500 );
function collision(basket_x, basket_y, ball_x, ball_y) {
if(balloon_y + 85 < basket_y) {
return false;
}
if (balloon_y > basket_y + 91) {
return false;
}
if (balloon_x + 80 < basket_x) {
return false;
}
if (balloon_x > basket_x + 80) {
return false;
}
return true;
}
// Code to stop the game when we're finished playing
function stop_game() {
}
//Code for the ball
function draw_balloon(x,y) {
var balloon_img=new Image();
balloon_img.src="balloon.png";
ctx.drawImage(balloon_img,x,y);
}
//Code for the basket
function draw_basket(x,y) {
var basket_img=new Image();
basket_img.src="basket.png";
ctx.drawImage(basket_img,x,y);
}
</script>
</div>
</article>
</section>
</body>
</html>
You have to change the variable for the mouselistener. So instead of
mycanv.addEventListener("mousemove",seenmotion, false);
you have to write this
c.addEventListener("mousemove",seenmotion, false);
This move the basket with the mouse, but the image isn't still right. You have to subtract half of width and height of the image from the x and y coordinate.
To fix your background you have to modify your CSS. the article and the section tag have both full width/height und an own background. This shouldn't be to hard to fix, just change the background of #c to black.
#c {
background-color: black;
}
Here's the jsfiddle: https://jsfiddle.net/pgkL09j7/10/
Visit http://www.w3schools.com/ for more information about CSS and JS. Also the code can be more easier and structured.
I want to use onmouseover in this javascript code. So, whenever I move the mouse over the square, the function changeColor executes and picks one color each time, from the two given colors.
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>
<body>
<h1>Canvas Art Gallary</h1>
<canvas id="myCanvas" width="400" height="300" style="border:10px solid #c3c3c3">
</canvas>
<script type="text/javascript">
function changeColor(){
ctx.fillStyle = "#FFFFFF";
ctx.fillStyle = "#04B45F";
}
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(150,100,100,100);
</script>
</body>
</html>
Thanks
Listen for mouse events and toggle the color on our own custom mouseenter
Note: the rect does not have mouseenter so we must custom build one.
Listen for mousemove events
On rect mouseenter: set a wasInside flag to true and changeColor() which toggles the rect color
On rect mouseleave: clear a wasInside flag to indicate the mouse has left the rect.
Example code and a Demo: http://jsfiddle.net/m1erickson/9GcbH/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color:ivory; }
#canvas{border:1px solid red;background-color:black;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();
var toggle=0;
var x=150;
var y=100;
var w=100;
var h=100;
var wasInside=false;
// draw the rect to start
ctx.fillStyle = "red";
ctx.fillRect(x,y,w,h);
function changeColor(){
if(toggle==0){
ctx.fillStyle = "#FFFFFF";
toggle=1;
}else{
ctx.fillStyle = "#04B45F";
toggle=0;
}
ctx.fillRect(x,y,w,h);
}
function handleMouseMove(e){
e.preventDefault();
var mx=parseInt(e.clientX-offsetX);
var my=parseInt(e.clientY-offsetY);
var isInsideNow=(mx>x && mx<x+w && my>y && my<=y+h);
if(isInsideNow && !wasInside){
changeColor();
wasInside=true;
}else if(!isInsideNow && wasInside){
wasInside=false;
}
}
$("#canvas").mousemove(function(e){handleMouseMove(e);});
}); // end $(function(){});
</script>
</head>
<body>
<h4>Rect color toggles white-green<br>each time mouse moves over it.</h4>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
[ Addition: explain steps of toggling ]
Each time the mouse enters the rect changeColor is called.
changeColor both changes the color and also changes toggle.
Here's a step-by-step:
1. toggle==0 at the beginning of the ap
2. mouse enters rect and changeColor is called.
3. changeColor changes color to #ffffff because toggle==0.
4. changeColor changes toggle=1
5. mouse exits rect
6. mouse enters rect again and changeColor is called again.
7. changeColor changes color to #04b45f because toggle==1.
8. changeColor changes toggle=0;
mouseover will only know when you're over the canvas, so you need to detect you're above the square (I'm using the variables already defined by you):
var sqx1 = c.offsetLeft + 150; //left top corner of the square respect to the window
var sqy1 = c.offsetTop + 100;
var sqx2 = sqx1 + 100; //right bottom corner of the square respect to the window
var sqy2 = sqy1 + 100;
var lastOverSquare = false;
c.addEventListener('mousemove', function(e) {
var overSquare =
(sqx1 <= e.pageX && sqx2 >= e.pageX) &&
(sqy1 <= e.pageY && sqy2 >= e.pageY);
if (overSquare && !lastOverSquare) changeColour(); //change only when it enters the square, not every move when we're already over it.
lastOverSquare = overSquare;
}, false);
var colours = ['#FFFFFF', '#04B45F'];
var currentColour = 0;
ctx.fillStyle = colours[currentColour];
function changeColour() {
currentColour = (currentColour + 1) % colours.length;
ctx.fillStyle = colours[currentColour];
}
I have this code in my project, here is the link: http://jsfiddle.net/89wgk/
This is my code:
<canvas id="myCanvas" width="188" height="200"></canvas>
var rectWidth = 110;
var rectHeight = 110;
var rectX = 10;
var rectY = 25;
When I put the mouse in curved rectangle starts the shadow, but I want that to happen when I put the mouse over the reeds (rectangle) and not within the canvas.
I wonder how do I run the shadow so when I move the mouse over the rectangle?
Here is how I would do it:
create a function that draws the arc shape because it must be redrawn often
listen for mouseMove events on the canvas
test whether the mouse is inside the arc with context.isPointInside(mouseX,mouseY)
redraw the arc with/without the shadow based on if the mouse is inside the arc
Have Fun!
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/64BHx/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var w = 110;
var h = 110;
var x = 10;
var y = 25;
var isShadowed=false;
context.strokeStyle="#FF2A2A";
context.shadowBlur = 20;
context.shadowOffsetX = 5;
context.shadowOffsetY = 5;
context.globalAlpha=.250;
context.strokeRect(x,y,w,h);
context.globalAlpha=1.00;
function draw(){
// clear the canvas
context.clearRect(0,0,canvas.width,canvas.height);
// save the context state
context.save();
// set/clear the shadow based on isShadowed
context.shadowColor= isShadowed ? '#7FD4FF' : "#FFFFFF";
// draw the arc shape
context.beginPath();
context.moveTo(x,y);
context.quadraticCurveTo(x+w-2,y+2,x+w,y+h);
context.lineTo(x+w-35,y+h);
context.quadraticCurveTo(x+w-2-35,y+2+35,x,y+35);
context.lineTo(x,y);
context.fillStyle="red";
context.fill();
context.stroke();
// restore the context state
context.restore();
}
// testing: display if mouse is in/out of arc shape
var $status=$("#status");
// listen for mousemove events
$("#canvas").mousemove(function(e){handleMouseMove(e);});
// handle mousemove events
function handleMouseMove(e){
// we alone are using mousemove events
e.preventDefault();
// get current mouse X/Y
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// hit test if mouse is inside the arc shape
var isInside=context.isPointInPath(mouseX,mouseY);
$status.text("Is mouse inside: "+isInside);
// don't redraw unless needed
if(isInside && isShadowed){return;}
if(!isInside && !isShadowed){return;}
// change the shadow and redraw
isShadowed=isInside;
draw();
}
// start by drawing the unshadowed arc
draw();
}); // end $(function(){});
</script>
</head>
<body>
<p id="status">Status</p><br>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
I would like to a particular shape on the canvas.
I have implemented a canvas on which we can draw shapes like rectangle, circle, line, ellipse and so on using mouse events.
I have created a drop down list with all the shapes that I am drawing on the canvas.
The drop down list consists of shapes like circle, rectangle, parallelogram, ellipse, circle...
Now what I want is, for example, think that I have drawn 2 rectangles and 2 circles. When I select circle shape from the drop down list and click undo button it should undo only the circles and if I select the rectangle shape from the drop down list and click on undo button it should undo only the rectangle shapes not the other shapes
the code that i am using for undo in the canvas is :
function cPush()
{
canvas = document.getElementById("drawingCanvas");
context = canvas.getContext("2d");
cStep++;
if (cStep < cPushArray.length)
{
cPushArray.length = cStep;
}
cPushArray.push(document.getElementById('drawingCanvas').toDataURL());
}
function cUndo()
{
canvas = document.getElementById("drawingCanvas");
context = canvas.getContext("2d");
context.clearRect(0,0,canvas.width, canvas.height);
if (cStep > 0)
{
cStep--;
var canvasPic = new Image();
canvasPic.src = cPushArray[cStep];
context.drawImage(canvasPic, 0, 0);
}
}
How to "undo" (remove a specified shape and redraw the remaining shapes)
Demo: http://jsfiddle.net/m1erickson/9pTJ2/
Create an array to hold all your shape definitions:
var drawings=[];
Add shapes to the array:
function addShape(shapename,color){
drawings.push({
shape:shapename,
color:color
});
drawAll();
}
To "undo", remove all elements of a specified shape from the array:
function undoShape(shapename){
var i=drawings.length-1;
while(i>=0){
if(drawings[i].shape==shapename){
drawings.splice(i,1);
}
i--;
}
drawAll();
}
Here is code:
[ props to #enhzflep for suggesting the method ]
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.lineWidth=1;
var shapeWidth=30;
var shapeHeight=30;
var spacer=5;
var drawings=[];
function addShape(shapename,color){
drawings.push({
shape:shapename,
color:color
});
drawAll();
}
function undoShape(shapename){
var i=drawings.length-1;
while(i>=0){
if(drawings[i].shape==shapename){
drawings.splice(i,1);
}
i--;
}
drawAll();
}
function drawAll(){
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<drawings.length;i++){
var drawing=drawings[i];
var x=i*shapeWidth;
var y=50;
switch(drawing.shape){
case "rectangle":
drawRectangle(x,y,drawing.color);
break;
case "circle":
drawCircle(x,y,drawing.color);
break;
}
}
}
function drawContainer(x,y){
ctx.strokeStyle="lightgray";
ctx.strokeRect(x,y,shapeWidth,shapeHeight);
}
function drawRectangle(x,y,color){
drawContainer(x,y);
ctx.fillStyle=color;
ctx.fillRect(x+spacer,y+spacer,shapeWidth-2*spacer,shapeHeight-2*spacer);
}
function drawCircle(x,y,color){
drawContainer(x,y);
ctx.beginPath();
ctx.arc(x+shapeWidth/2,y+shapeHeight/2,shapeWidth/2-spacer,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle=color;
ctx.fill();
}
function randomColor(){
return('#'+Math.floor(Math.random()*16777215).toString(16));
}
$("#rect").click(function(){
addShape("rectangle",randomColor());
});
$("#circle").click(function(){
addShape("circle",randomColor());
});
$("#norect").click(function(){
undoShape("rectangle");
});
$("#nocircle").click(function(){
undoShape("circle");
});
}); // end $(function(){});
</script>
</head>
<body>
<button id="rect">Add Rect</button>
<button id="circle">Add Circle</button>
<button id="norect">Erase Rects</button>
<button id="nocircle">Erase Circles</button>
<canvas id="tools" width=300 height=40></canvas><br>
<canvas id="erasers" width=300 height=40></canvas><br>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
I'd like to show a mouse tooltip like this:
with a coordinate system relative to its image.
Whenever the mouse is hovered over one of the 75x75 cells, the position is displayed in text. I can only show the mouse's raw coordinates, but can't figure out the math to display it like it is in the picture.
I'm open to HTML5 implementations as well.
Here’s how to convert mouse coordinates to cell coordinates and display a tooltip
This math calculates which 75x75 cell your mouse is inside:
var col=parseInt(mouseX/75);
var row=parseInt(mouseY/75);
And here is the math to calculate a tip rectangle in the upper-right of that cell:
var tipX=tipCol*75+75-tipWidth;
var tipY=tipRow*75;
You can use canvas to draw the tip inside the cell at your calculated coordinates:
function tip(x,y){
var tipX=tipCol*75+75-tipWidth;
var tipY=tipRow*75;
ctx.beginPath();
ctx.rect(tipX,tipY,tipWidth,tipHeight);
ctx.fillStyle="ivory";
ctx.fill();
ctx.fillStyle="blue";
ctx.fillText(tipCol+","+tipRow,tipX+2,tipY+17);
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/9V5QK/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:25px;}
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var startX;
var startY;
var isDown=false;
var tipWidth=35;
var tipHeight=22;
var tipRow;
var tipCol;
ctx.font="14pt verdana";
draw();
function draw(){
// you would just draw your image here
// ctx.drawImage(0,0,image.width,image.height);
// but for illustration, this just recreates your image
ctx.beginPath();
ctx.rect(0,0,375,225);
for(var x=1;x<5;x++){ ctx.moveTo(x*75,0); ctx.lineTo(x*75,canvas.height); }
for(var y=1;y<3;y++){ ctx.moveTo(0,y*75); ctx.lineTo(canvas.width,y*75); }
ctx.fillStyle="black";
ctx.fill();
ctx.strokeStyle="gray";
ctx.lineWidth=2;
ctx.stroke();
}
function tip(x,y){
var tipX=tipCol*75+75-tipWidth;
var tipY=tipRow*75;
ctx.beginPath();
ctx.rect(tipX,tipY,tipWidth,tipHeight);
ctx.fillStyle="ivory";
ctx.fill();
ctx.fillStyle="blue";
ctx.fillText(tipCol+","+tipRow,tipX+2,tipY+17);
}
function handleMouseMove(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#movelog").html("Move: "+ mouseX + " / " + mouseY);
// Put your mousemove stuff here
var col=parseInt(mouseX/75);
var row=parseInt(mouseY/75);
if(!(row==tipRow && col==tipCol)){
tipCol=col;
tipRow=row;
draw();
tip();
}
}
$("#canvas").mousemove(function(e){handleMouseMove(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Move mouse over grid to display current cell</p>
<p id="movelog">Move</p>
<canvas id="canvas" width=375 height=225></canvas>
</body>
</html>