CSS3 border radius to HTML5 Canvas - javascript

I trying to reproduce the CSS3 border radius in canvas.
It's easy to draw a rounded rectangle but in CSS, the value of each border can be high.
For example :
HTML
<div class="normal_radius"></div>
<div class="high_radius"></div>
<div class="high2_radius"></div>
CSS
div { height:50px;width:50px;position:absolute;top:10px; }
.normal_radius {
border: 1px solid black;
border-radius: 5px 5px 10px 15px;
left: 10px;
}
.high_radius {
border: 1px solid red;
border-radius: 5000px 500px 100px 150px;
left: 80px;
}
.high2_radius {
border: 1px solid blue;
border-radius: 2500px 250px 50px 75px;
left: 160px;
}
Here a jsfiddle
The black, normal border radius value, i can reproduce that.
The red, high value for border radius, i don't know how reproduce that.
And the blue, high value divided by 2, same result of red.
My question is simple, how to reproduce the red and the blue in canvas?
Best regards.

The function below is pretty close. Although if you use values greater than the width and height you're going to have issues.
Live Demo
function canvasRadius(x, y, w, h, tl, tr, br, bl){
var r = x + w,
b = y + h;
ctx.beginPath();
ctx.moveTo(x+tl, y);
ctx.lineTo(r-(tr), y);
ctx.quadraticCurveTo(r, y, r, y+tr);
ctx.lineTo(r, b-br);
ctx.quadraticCurveTo(r, b, r-br, b);
ctx.lineTo(x+bl, b);
ctx.quadraticCurveTo(x, b, x, b-bl);
ctx.lineTo(x, y+tl);
ctx.quadraticCurveTo(x, y, x+tl, y);
ctx.stroke();
}
canvasRadius(10,10,50,50,5,5,10,15);
ctx.strokeStyle = "red";
canvasRadius(80,10,50,50,47,3,0,0);
ctx.strokeStyle = "blue";
canvasRadius(160,10,50,50,47,3,0,0);

here the solution :
CanvasRenderingContext2D.prototype.roundRect=function(x,y,width,height,tl,tr,br,bl) {
var x1,x2,x3,x4,y1,y2,y3,y4,radii,ratio=0,CURVE2KAPPA=0.5522847498307934;
ratio=Math.min(Math.min(width/(tl+tr),width/(br+bl)),Math.min(height/(tl+bl),height/(tr+br)));
if ((ratio>0)&&(ratio<1)) {
tl*=ratio;
tr*=ratio;
bl*=ratio;
br*=ratio;
}
xw=x+width;
yh=y+height;
x1=x+tl;
x2=xw-tr;
x3=xw-br;
x4=x+bl;
y1=y+tr;
y2=yh-br;
y3=yh-bl;
y4=y+tl;
this.beginPath();
this.moveTo(x1,y);
this.lineTo(x2,y);
radii=CURVE2KAPPA*tr;
this.bezierCurveTo(x2+radii,y,xw,y1-radii,xw,y1);
this.lineTo(xw,y2);
radii=CURVE2KAPPA*br;
this.bezierCurveTo(xw,y2+radii,x3+radii,yh,x3,yh);
this.lineTo(x4,yh);
radii=CURVE2KAPPA*bl;
this.bezierCurveTo(x4-radii,yh,x,y3+radii,x,y3);
this.lineTo(x,y4);
radii=CURVE2KAPPA*tl;
this.bezierCurveTo(x,y4-radii,x1-radii,y,x1,y);
this.stroke();
}
ctx.roundRect(0,0,50,50,5,5,10,15);
ctx.strokeStyle="red";
ctx.roundRect(0,0,50,50,5000,500,100,150);
ctx.strokeStyle="blue";
ctx.roundRect(0,0,50,50,2500,250,50,75);
Live demo
Have fun.

Related

Javascript unable to capture the mouse position in dedicated variables, when I can easily print it out

So, I am getting back into javascript coding, and I am resuming an older project. I am attempting to capture the mouse position in dedicated variables (mouseX and mouseY), for ease of use.
I have successfully managed to print out the mouse coordinates in real time, but when I try to place those coordinates into dedicated variables for ease of use, the program fails.
I believe this is most likely a simple syntax error, but I don't know where else to look for what I'm doing wrong.
This code fragment works correctly:
document.addEventListener('mousemove', (event) => {
document.getElementById("fiddleText").innerHTML = (`Mouse X: ${event.clientX}, Mouse Y: ${event.clientY}`);
})
However, when I try to store the mouse position in two variables, like so:
document.addEventListener('mousemove', (event) => {
mouseX = event.ClientX;
mouseY = event.ClientY;
document.getElementByID("fiddleText").innerHTML = (`Mouse X: `+ mouseX + `Mouse Y: ` + mouseY);
})
the program fails.
Note: I've updated the second code fragment to fix a syntax error that was brought to my attention, but it still doesn't work.
The original second fragment looked like this:
document.addEventListener('mousemove', (event) => {
mouseX = ${event.clientX};
mouseY = ${event.clientY};
document.getElementByID("fiddleText").innerHTML = (`Mouse X: `+ mouseX + `Mouse Y: ` + mouseY);
})
I'd like to imagine that my question can be answered using only the code shown above, but last time I believed that, I was mistaken. As such, I have pasted my full javascript program below.
Note: This program is a work-in-progress, and there is a comment header stating "this is the problem area"; ignore this for now, that is an unrelated issue. Right now, I'm just trying to get the mouse to work.
//canvas elements
var canvas = document.getElementById("SnekGamCanvas");
var ctx = canvas.getContext("2d");
canvas.addEventListener('click', function () { }, false);
/*
//some code from stack overflow: (https://stackoverflow.com/questions/9880279/how-do-i-add-a-simple-onclick-event-handler-to-a-canvas-element)
var elem = document.getElementById('canvas'),
elemLeft = elem.offsetLeft + elem.clientLeft,
elemTop = elem.offsetTop + elem.clientTop,
context = elem.getContext('2d'),
elements = [];
// Add event listener for `click` events.
elem.addEventListener('click', function (event) {
var x = event.pageX - elemLeft,
y = event.pageY - elemTop;
// Collision detection between clicked offset and element.
elements.forEach(function (element) {
if (y > element.top && y < element.top + element.height
&& x > element.left && x < element.left + element.width) {
alert('clicked an element');
}
});
}, false);
// Add element.
elements.push({
colour: '#05EFFF',
width: 150,
height: 100,
top: 20,
left: 15
});
// Render elements.
elements.forEach(function (element) {
context.fillStyle = element.colour;
context.fillRect(element.left, element.top, element.width, element.height);
});
*/
//End of code from stack overflow
//some important variables
var px = canvas.width / 2;
var py = canvas.height / 2;
var snekColor = "#EC942D";
var clock = 0;
var mouseX = 0.5;
var mouseY = 0.5;
//classes
class clickButton {
constructor(text, color, width, height, radius) {
this.text = text;
this.color = color;
this.width = width;
this.height = height;
this.radius = radius;
}
drawButton(xpos, ypos) {
ctx.strokeStyle = "#000000"
ctx.fillStyle = this.color;
roundRect(xpos, ypos, this.width, this.height, this.radius, true, true, this.color);
ctx.fillStyle = "#000000";
ctx.strokeStyle = "#000000";
ctx.font = '40px san-serif';
ctx.strokeText(this.text, xpos + 10, ypos + 40);
ctx.fillText(this.text, xpos + 10, ypos + 40);
//draw_Ball(303, 500, 50, snekColor);
}
clickOnButton() {
}
}
//buttons
var startButton = new clickButton("Start Game", "#74B5ED", 200, 50, 20);
//images
var seel = new Image();
seel.onload = function () {
ctx.drawImage(seel, 0, 0, canvas.width, canvas.height);
}
seel.src = "https://assets.pokemon.com/assets/cms2/img/pokedex/full/086.png"
var snek_title = new Image();
snek_title.onload = function () {
ctx.drawImage(snek_title, 0, 0, canvas.width, canvas.height);
}
snek_title.src = "https://globin347.com/images/Snake%20Title.png"
//stuff about mouse moving
document.addEventListener('mousemove', (event) => {
//document.getElementById("fiddleText").innerHTML = (`Mouse X: ${event.clientX}, Mouse Y: ${event.clientY}`);
mouseX = event.ClientX;
mouseY = event.ClientY;
document.getElementByID("fiddleText").innerHTML = (`Mouse X: `+ mouseX + `Mouse Y: ` + mouseY);
})
//begin
var gameState = 0;
function draw() {
clock += 1;
ctx.clearRect(0, 0, canvas.width, canvas.height);
//document.getElementById("fiddleText").innerHTML = ("Clock: " + clock);
if (gameState == 0) {
//this hasn't been implemented yet
startMenu();
}
else if (gameState == 1) {
//this hasn't been implemented yet either
playGame();
}
else if (gameState == 2) {
//ditto
gameOver();
}
else {
//something's wrong
ctx.drawImage(seel, 0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#b30000";
ctx.strokeStyle = "#000000";
ctx.font = '140px san-serif';
ctx.fillText('OH NO', 120, 120);
ctx.strokeText('OH NO', 120, 120);
ctx.fillText('IT BLOKE', 200, 630);
ctx.strokeText('IT BLOKE', 200, 630);
}
}
setInterval(draw, 10);
function startMenu() {
ctx.drawImage(snek_title, 0, 0, canvas.width, canvas.height);
/***********************************************
*
*
* This is the problem area. When the next line, startButton.drawButton(100, 100) is commented out, the rest of the code workes normally.
* However, if the line is not commented out, draw_Ball doesn't run, indicating that the program crashed somewhere in the button code.
* I would like to reiterate that the button's functionality has not yet been implemented; I am only trying to get it to display.
*
*
**********************************************/
//startButton.drawButton((canvas.width / 2) - 100, (canvas.height * (4 / 5)));
//flashing lights
/*flashTime = timer % 100;
if (timer % 2) {
draw_Ball(200, 700, 50, snekColor);
}*/
draw_Ball(200, 700, 50, snekColor);
}
function playGame() {
draw_Ball(200, 700, 50, snekColor);
draw_Ball(400, 700, 50, snekColor);
draw_Ball(300, 500, 50, snekColor);
}
function gameOver() {
}
//this function was stolen from stack overflow
function showImage(width, height, image_source, alt_text) {
var img = document.createElement("img");
img.src = image_source;
img.width = width;
img.height = height;
img.alt = alt_text;
}
function draw_Ball(bx, by, size, ballColor) {
ctx.beginPath();
ctx.arc(bx, by, size, 0, (Math.PI * 2));
ctx.fillStyle = ballColor;
ctx.fill();
ctx.strokeStyle = "#000000";
ctx.stroke();
ctx.closePath();
}
//This next function was taken from stack overflow
function roundRect(x, y, width, height, radius, stroke, fill, color) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
if (stroke) {
ctx.stroke();
}
if (fill) {
ctx.fill();
}
ctx.closePath();
return;
}
And, for good measure, my HTML and CSS files:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - Portfolio</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body class="background_gradient">
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-dark dark-bg border-bottom box_shadow mb-0">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Portfolio</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<!--
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
-->
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Resume">Resume</a>
</li>
<!----
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Art3D">3D Art</a>
</li>
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Art2D">2D Art</a>
</li>
<!---->
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Snake">Snake</a>
</li>
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="CodeExamples">Code Examples</a>
</li>
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Ballad">Ballad of the Masked Bandits</a>
</li>
<!--
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="DataBaseHub">Database Hub</a>
</li>
--->
<!--
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Unavailable">???</a>
</li>
-->
<!--Temporary Links-->
</ul>
</div>
</div>
</nav>
</header>
<div class="container-fluid" id="MainDiv">
<main role="main" class="pb-0" style="width:100%">
<!--Where the other code goes-->
#{
ViewData["Title"] = "Snake Game";
}
<div class="container-fluid purple_gradient text-center">
<h1>Snake Game</h1>
</div>
<div class="buffer"></div>
<div class="container">
<div class="fancy_text_box">
<div class="container buffer">
<div class="ghostly_text_box text-center">
<h1>By the power of Javascript, here is a playable snake game.</h1>
<div class="buffer"></div>
<h1 id="fiddleText">Give it a moment to load.</h1>
</div>
<div class="buffer"></div>
<div class="ghostly_text_box text-center">
<canvas onload="draw()" class="simple_text_box" id="SnekGamCanvas" width="1000" height="1000"></canvas>
</div>
</div>
</div>
<div class="text-center">
<div class="buffer"></div>
<a class="button glo_button big_r_button big_text" asp-area="" asp-controller="Home" asp-action="Index">Back to Home</a>
<div class="buffer"></div>
</div>
<!--The code be here but if you are reading this you probably already knew that-->
<script src="~/js/Snake.js"></script>
</div>
</main>
</div>
<footer class="border-top footer dark-bg text-light">
<div class="container">
© 2021 - Portfolio - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<script src="../jsc3d-master/jsc3d/jsc3d.js"></script>
#RenderSection("Scripts", required: false)
</body>
</html>
...
/* Please see documentation at https://learn.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
/* Provide sufficient contrast against white background */
a {
color: #0366d6;
}
.btn-primary {
color: #fff;
background-image: linear-gradient(30deg, #b6e2dd, #2a5efe);
border-color: #1861ac;
}
/*Link colors*/
.nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
/* Sticky footer styles
-------------------------------------------------- */
html {
font-size: 14px;
}
#media (min-width: 768px) {
html {
font-size: 16px;
}
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
/* Sticky footer styles
-------------------------------------------------- */
html {
position: relative;
min-height: 100%;
}
body {
/* Margin bottom by footer height */
margin-bottom: 60px;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
white-space: nowrap;
line-height: 60px; /* Vertically center the text there */
}
/* My Stuff
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
*/
/*This gives me more control over the exact dark background color*/
.dark-bg
{
background-color: #161631;
}
.purple_gradient
{
/*The image used*/
background-image: linear-gradient(#4b1ac4, #fff);
height:100%;
width:100%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.test_box_blue
{
/* A container with a solid color and an outline */
background-color: #2d1eb2;
width: 100%;
height: 100%;
margin: 0px;
}
.test_box
{
border:solid #000000;
}
#MainDiv
{
padding:0;
margin:0;
left:0;
top:0;
width:100%;
height:100%;
}
.tundra_backround
{
background-image: url('../images/Tundra_Fixed.png');
width:100%;
height:100%;
}
.white_space_box
{
height:50 px;
}
.background_gradient
{
background-image:linear-gradient(320deg, #fff, #96cbde);
}
.glo_button
{
min-width: 30%;
height: 20%;
border-radius: 25px;
padding: 20px;
margin: 10px;
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
transition-duration: 0.4s;
border: 4px solid #000;
}
.big_r_button {
background-color: #a10000;
color: #fff;
}
.big_r_button:hover {
color: #fff;
background-color: #4e0505;
}
.big_b_button {
background-color: #080e9f;
color: #fff;
}
.big_b_button:hover {
color: #fff;
background-color: #161631;
}
.big_g_button {
background-color: #0a7727;
color: #fff;
}
.big_g_button:hover {
color: #fff;
background-color: #07340e;
}
.big_p_button {
background-color: #6f1cbf;
color: #fff;
}
.big_p_button:hover {
color: #fff;
background-color: #2a073e;
}
.buffer
{
padding: 20px;
}
.big_text
{
font-size: 60px;
font-family:'Times New Roman', Times, serif;
text-shadow: 2px 2px rgb(12 14 39 / 0.67);
}
.fancy_text_box{
background-image: linear-gradient(300deg, #ece1c4, #c99e69);
border-radius: 25px;
border: 4px solid #5d3c08;
}
.simple_text_box{
background-color: #fff;
border: 2px solid #000;
}
.ghostly_text_box{
background-color: rgb(255 255 255 / 0.60);
border-radius: 25px;
padding: 10px;
border: 3px solid #000;
}
.thick_border{
border: 4px solid #000;
}
.black_and_white_gradient{
background-image: linear-gradient(310deg, #fff, #000);
}
.red_border{
padding: 0px;
margin: 0px;
border: 4px solid #8f0000;
}
.model_box{
border: 4px solid #000;
background-color: #fff;
border-radius: 25px;
}
.image_box{
border: 4px solid #000;
background-color: #fff;
}
.chain_image_box {
border-top: 4px solid #000;
border-left: 4px solid #000;
border-right: 4px solid #000;
border-bottom: 0px;
background-color: #fff;
}
.margin_setter {
margin: 20px;
padding: 20px;
}
#model_display_1{
}
I apologize for asking such a simple question, but I don't know where to look to find an existing answer.
So, as I suspected, it was a simple syntax error.
Specifically, I wrote "getElementByID" instead of "getElementById". a capitalization error. (I also capitalized "clientX" and "clientY", which also broke stuff.)
I couldn't see it because I was using Visual Studio, and I couldn't find the output for the javascript. By copying the code and pasting it into JS Fiddle, I was able to actually see the errors being generated by the Javascript.
I guess that means that until I find a way to see javascript errors when running HTML code via Visual Studio, I will need to do some debugging via JS Fiddle.

Change background image of div when mouse has specific class

I'm creating an interactive art piece, which people can collaborate on. What I want is that there is a library of icons people can use. And when clicking on them, the mouse gets a class and thus when clicking on a specific cell in the table, the cell will get the icon as their background image.
(Now I know I will need a database etc, but that's for later. First things first.)
I did something similar a long time ago, but I don't know how to edit this in order to work for this project:
function nextPic() {
if ( $('html,body').css('cursor').indexOf('cursor2.png') > 0 )
{
counter += 1;
if (counter > myPictures.length - 1) {
// counter = 0;
}
else {
element.style.backgroundImage = "url(" + myPictures[counter] + ")";
}
}
It just works according to the image on the cursor. Not ideal at all, it bugged ALL the time.
I've looked at a code for pixel art, which (kind of) does what needs t one done. But not quite.
The pixel art fiddle here:
https://jsfiddle.net/bxstmufj/
So here is an example of someone doing what you want but instead of in a table grid in a canvas. Mad props to them for putting this out:
http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/
After the basic drawing on a canvas they add the ability to pick colors. Notice how they save the picked color into a variable that is then called on for the canvas reDraw() function.
The same thing can be done with icons. Simply having an onClick event for whatever icon is clicked just like they did with colors (in their case they chose mousedown event):
$('#choosePurpleSimpleColors').mousedown(function(e){
curColor_simpleColors = colorPurple;
});
That is the event handler they put on the purple button for example. You can see this by inspecting the element (button) then on the right click Event Handlers then go to the mousedown event and then you can click on the javascript file location where this code is. (All of this done in chrome inspect{right click, then pick inspect})
Now if you did not want to do it on a canvas but instead a a table/grid all you would do is set onClick events for the cells. They would then call on the color/icon variable and set them for that cell.
Let me know if you would like an example for a grid/table. The canvas is a bit more of a complex answer but I suspect it is what you really prefer. The second example and beyond is really what you want so you could also pick icons to insert.
context = document.getElementById('canvas').getContext("2d");
$('#canvas').mousedown(function(e){
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
$('#canvas').mousemove(function(e){
if(paint){
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
redraw();
}
});
$('#canvas').mouseup(function(e){
paint = false;
});
$('#canvas').mouseleave(function(e){
paint = false;
});
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
function addClick(x, y, dragging)
{
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
}
function redraw(){
context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas
context.strokeStyle = "#df4b26";
context.lineJoin = "round";
context.lineWidth = 5;
for(var i=0; i < clickX.length; i++) {
context.beginPath();
if(clickDrag[i] && i){
context.moveTo(clickX[i-1], clickY[i-1]);
}else{
context.moveTo(clickX[i]-1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.stroke();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="canvas" width="490" height="220" style="border: solid 1px black;"></canvas>
Fixed!
<div id="p1" class="pen"></div>
<div id="p2" class="pen"></div>
<div id="art">
<div class="row">
<div class="pixel"></div>
<div class="pixel"></div>
</div>
</div>
icon = '(icon.png)'
$('#p1').click(function (){
icon = "icon2.png";
alert(icon);
});
$('#p2').click(function (){
icon = "icon3.png";
alert(icon);
});
// onclick function classes
$(".pixel").click(function() {
//function that changes background to url
// $(this).css('background-image', var(icon));
// $(this).css("background-image", "url(" + icon")");
$(this).css("background-image", "url(" +icon +")");
});
#art {
display: table;
border-spacing: 1px;
background-color: black;
border: 1px solid black;
}
.row {
display: table-row;
}
.pixel {
display: table-cell;
background-color: white;
width: 25px;
margin: 1px;
height: 25px;
background-size: contain;
}
.pen {
display: inline-block;
width: 40px;
height: 40px;
border: 2px solid black;
}
I don't know about using a class to set varied colors; a class would infer that they are all the same. You'd have to use ids to differentiate. You could pass the id and the color that you want to change the background to to a function and work it that way. Or you might opt to put the colors in an array and use the index number?
I made a basic example using the squares in your fiddle, to give an idea. As you can see, I only assigned one of the two a background value using css. The function can be tweaked to change background image if you want to use images instead of colors of course..
Hope this helps
function setPenColour(id, pixel) {
var myDiv = document.getElementById(id);
myDiv.style.backgroundColor = pixel;
}
#p1 {
background-color: grey;
}
#art {
display: table;
border-spacing: 1px;
background-color: black;
border: 1px solid black;
}
.row {
display: table-row;
}
.pixel {
display: table-cell;
background-color: white;
width: 25px;
margin: 1px;
height: 25px;
}
.pen {
display: inline-block;
width: 40px;
height: 40px;
border: 2px solid black;
}
<div id="p1" class="pen" onclick="setPenColour(id, '#00FF00')" ;></div>
<div id="p2" class="pen" style="background-color:blue;" onclick="setPenColour(id, 'red')"></div>

make a shape in canvas appear after 5s

I have 2 circles in the html canvas element, which I drew with Javascript. I want to make the first circle appear after 5 seconds.
I was wondering if you need to do this with Javascript and if so, how do you do this?
See the code for reference:
var c = document.getElementById("canvas1");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(30, 75, 20, 0,Math.PI*2);
ctx.stroke();
ctx.closePath;
ctx.beginPath();
ctx.arc(100,75,20,0,Math.PI*2);
ctx.stroke();
ctx.closePath();
#canvas1{
width: 300px;
height: 150px;
border: 1px solid black;
margin-top: 100px;
}
<canvas id="canvas1"></canvas>
use setTimeout method when the shape is created
setTimeout(function() {
ctx.beginPath();
ctx.arc(30, 75, 20, 0,Math.PI*2);
ctx.stroke();
ctx.closePath;
ctx.beginPath();
ctx.arc(100,75,20,0,Math.PI*2);
ctx.stroke();
ctx.closePath();
},5000)
You can use global function setTimeout, e.g. like this:
var c = document.getElementById("canvas1")
var ctx = c.getContext("2d")
function circle(a1, a2, a3, a4) {
ctx.beginPath()
ctx.arc(a1, a2, a3, a4 ,Math.PI*2)
ctx.stroke()
ctx.closePath()
}
setTimeout(circle, 5000 /*time in ms*/, 30, 75, 20, 0)
circle(100, 75, 20, 0)
#canvas1{
width: 300px;
height: 150px;
border: 1px solid black;
margin-top: 100px;
}
<canvas id="canvas1"></canvas>

Javascript - mouse follow + Lighting?

I'm practicing my Javascript, so i made a follow-mouse function. I got it working, but now i have a new idea, which i'm not sure is possible.
Is there a way, to make a '' orb of vision '' follow the mouse, so that everything in that area gets visible?. Kind of like using a torch, to see a small area where your mouse is.
NOTE : I'm not asking for someone to code it for me, but rather a explanation, since i'm curious to learn it myself, but i do need a guide-line!**
function mouseMovement(e) {
var x = document.getElementById('x_show');
var y = document.getElementById('y_show');
x.innerHTML = e.clientX;
y.innerHTML = e.clientY;
document.getElementById("followDiv").style.left = event.clientX - 15 + "px";
document.getElementById("followDiv").style.top = event.clientY - 15 + "px";
}
document.onmousemove = mouseMovement;
#followDiv {
background-color: lightblue;
height: 30px;
width: 30px;
position: absolute;
}
<p id="x_show">0</p>
<p id="y_show">0</p>
<div id="followDiv"></div>
A non-canvas way would be :
Set page background to black
Round the borders of #followDiv using 'border-radius: 50%;'
Set the background of this div to image
Play with the background-position to move opposite to mouse
Edit:
A final touch by softening the edges using box-shadow
function mouseMovement(e) {
var x = document.getElementById('x_show');
var y = document.getElementById('y_show');
x.innerHTML = e.clientX;
y.innerHTML = e.clientY;
var followDiv = document.getElementById("followDiv");
followDiv.style.left = event.clientX - 60 + "px";
followDiv.style.top = event.clientY - 60 + "px";
followDiv.style.backgroundPositionX = (-event.clientX) + 'px';
followDiv.style.backgroundPositionY = (-event.clientY) + 'px';
}
document.onmousemove = mouseMovement;
body {
background: black;
}
#followDiv {
background-color: lightblue;
height: 120px;
width: 120px;
position: absolute;
border-radius: 50%;
box-shadow: 0 0 12px 12px black inset, /* workaround for a soft edge issue :
http://stackoverflow.com/a/37460870/5483521
*/
0 0 2px 2px black inset, 0 0 2px 2px black inset, 0 0 2px 2px black inset;
background: url(https://dl.dropboxusercontent.com/u/139992952/multple/annotateMe.jpg) no-repeat;
}
<p id="x_show">0</p>
<p id="y_show">0</p>
<div id="followDiv"></div>
#Bulent Vural, this was my solution. But i can't get the circle ' smaller ' since i have to re-size it to fit the screen, which won't work with %'s.
The only way this works, is adding alot of " black, black, black ". Which isn't very pleasing.
function mouseMovement(e)
{
var x = document.getElementById('x_show');
var y = document.getElementById('y_show');
x.innerHTML = e.clientX;
y.innerHTML = e.clientY;
document.getElementById("followDiv").style.left = event.clientX-2000+"px";
document.getElementById("followDiv").style.top = event.clientY-2000+"px";
}
document.onmousemove = mouseMovement;
</script>
html, body {margin: 0; height: 100%; overflow: hidden}
#followDiv {
/* background-color: lightblue; */
height: 4000px;
width: 4000px;
position: absolute;
background: -webkit-radial-gradient(circle, rgba(248, 255, 252, 0),black);
background: -o-radial-gradient(circle, rgba(248, 255, 252, 0),black);
background: -moz-radial-gradient(circle, rgba(248, 255, 252, 0),black);
background: radial-gradient(circle, rgba(248, 255, 252, 0),black);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p id="x_show">0</p>
<p id="y_show">0</p>
<div id="followDiv"></div>
</body>
i think this could help you what you want.
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
$("#canvas").mousemove(function(e){handleMouseMove(e);});
var radius=30;
var img=new Image();
img.onload=function(){
draw(150,150,30);
}
img.src='https://dl.dropboxusercontent.com/u/139992952/multple/annotateMe.jpg'
function draw(cx,cy,radius){
ctx.save();
ctx.clearRect(0,0,cw,ch);
var radialGradient = ctx.createRadialGradient(cx, cy, 1, cx, cy, radius);
radialGradient.addColorStop(0, 'rgba(0,0,0,1)');
radialGradient.addColorStop(.65, 'rgba(0,0,0,1)');
radialGradient.addColorStop(1, 'rgba(0,0,0,0)');
ctx.beginPath();
ctx.arc(cx,cy,radius,0,Math.PI*2);
ctx.fillStyle=radialGradient;
ctx.fill();
ctx.globalCompositeOperation='source-atop';
ctx.drawImage(img,0,0);
ctx.globalCompositeOperation='destination-over';
ctx.fillStyle='black';
ctx.fillRect(0,0,cw,ch);
ctx.restore();
}
function handleMouseMove(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
draw(mouseX,mouseY,30);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Move mouse to reveal image with "flashlight"</h4>
<canvas id="canvas" width=300 height=300></canvas>

Hover events on element covered by higher z-index?

I have a canvas element (canvas-mouse) that spans the whole screen - its purpose is to draw a 50% opacity circle around the mouse of a certain size (grabsize). Also on the page will be a number of images in divs. I want these images to be clickable/hoverable, but I also want the 50% opacity circle in canvas-mouse to appear on top of them.
Is there any way to accomplish this?
HTML:
<canvas id="canvas-mouse" class="fullscreen"></canvas>
<div class="object die"><img src="images/Die_d6.svg"></div>
CSS:
html, body {
width: 100%;
height: 100%;
margin: 2px;
overflow: hidden;
color: #FFFFFF;
background-color: #2C744C;
}
canvas.fullscreen {
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
}
.object {
position: absolute;
}
#canvas-mouse {
z-index: 10;
}
JavaScript:
CanvasRenderingContext2D.prototype.drawCircle = function(xpos, ypos, radius, linewidth, linecolor, fill) {
if(typeof(linewidth)==="undefined") {
linewidth = 1;
}
if(typeof(linecolor)==="undefined") {
linecolor = "#000000";
}
this.beginPath();
this.arc(xpos, ypos, radius, 0, 2*Math.PI, false);
this.lineWidth = linewidth;
if(typeof(fill)!=="undefined") {
this.fillStyle = fill
this.fill();
}
this.strokeStyle = linecolor;
this.stroke();
}
CanvasRenderingContext2D.prototype.maximize = function() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
mousectx = $("#canvas-mouse")[0].getContext("2d");
mousectx.maximize();
//Dice handlers
$(".object.die").hover(function() {
//Hover event goes here
})
$(".object.die").mousedown(function() {
//Click event goes here
})
//Mouse movement handler
$(document).mousemove(function(e){
//Get the mouse positions and put them in {mouse}
mouse.x = e.pageX;z
mouse.y = e.pageY;
//Redraw the grab circle
mousectx.clearCanvas();
mousectx.drawCircle(mouse.x,mouse.y,grabsize,1,"#000000","rgba(0,0,255,0.5)");
});
Thanks in advance.
Try using pointer-events: none. This rule tells the browser to ignore an element. Mouse events won't be received by it, but will 'pass through'.
#canvas-mouse {
z-index: 10;
pointer-events: none;
}

Categories

Resources