html5,canvas,transition,gradient,smooth , How to display a smoother gradient in HTML5 canvas?

How to display a smoother gradient in HTML5 canvas?


Tag: html5,canvas,transition,gradient,smooth

I have a html5 canvas in my web page. I have only put an image and a gradient in it.

Canvas uses thic JS code to draw itself:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect ( 0 , 0 , canvas.width, canvas.height );
var img = document.getElementById("slika");
ctx.drawImage(img, 0, 0,canvas.width,canvas.height);
var grd = ctx.createLinearGradient(x-400, 0, x, 0)
grd.addColorStop(0.3,"hsla(360, 100%, 100%, 0)");
grd.addColorStop(1,"hsla(360, 100%, 100%, 0.8)");

ctx.font = "70px Arial";
ctx.fillStyle = "black"
ctx.textAlign = "right";

When it displays, the transition isn't very smooth, it just starts somewhere and ends somewhere.

It looks like this:

I would like the transition to be smoother(I don't mean a wider gradient).

Is there any way to do that?

Thanks for answering.


Use a s-slope based gradient which could be defined using an ease-in-out function. This way the transition between flat and linear is smoothed out. You may need to compensate a little on the width as initial and final values are closer to the flat values than in the linear approach.




var ctx = document.querySelector("canvas").getContext("2d"), img = new Image();
img.onload = function() {

  // init canvas and image
  ctx.canvas.width = this.naturalWidth;
  ctx.canvas.height = this.naturalHeight;
  ctx.drawImage(this, 0, 0);
  // gradient using ease-in-out
  var comp = 100;
  var grd = ctx.createLinearGradient(550 - comp, 0, 700 + comp, 0);
  for(var t = 0; t <= 1; t += 0.02) {    // convert linear t to "easing" t:
    grd.addColorStop(t, "hsla(360, 100%, 100%, " + easeInOut(t) * 0.8 + ")");
  ctx.fillStyle = grd;
  ctx.fillRect(0,0, ctx.canvas.width, ctx.canvas.height * 0.5);

  // linear (as before)
  var grd = ctx.createLinearGradient(550, 0, 700, 0);
  grd.addColorStop(0, "hsla(360, 100%, 100%, 0)");
  grd.addColorStop(1, "hsla(360, 100%, 100%, 0.8)");
  ctx.fillStyle = grd;
  ctx.fillRect(0,ctx.canvas.height * 0.5+1, ctx.canvas.width, ctx.canvas.height * 0.5);

function easeInOut(t) {return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1}

img.src = "";
canvas {width:100%; height:auto}


Regex not working in HTML5 pattern

So I have this regex intended to let pass all text but those that contain as initial chars the "34" sequence: ^(?!34)(?=([\w]+)) The regex is working fine for me in , check the tests to see the intended behavior. Any Idea why it isn't working in my form? <form>...

Show only the requested forms using JS

As the image below illustrates, I have two forms and two buttons. Currently all the forms are visible. How can I only show the requested form "according to the option they have selected (from the blue buttons on the top)"? So, if the user clicked on the "send an invite"...

customize the handler of input range

When we use input range <input type="range", there is a handler which is moveable as how we handle it. Now I need a help how to customize this handle, in this case I want to change the default handler with my own handler(image of button). Thanks for the help <input...

CSS drop down navigation

I'm sure this is something simple I'm missing... My drop down menu is opening within the main navigation, widening it. Here is a link to the page I'm working on. The issue is with the navigation below the App buttons. Here is my HTML: <div class="container-fluid"> <div class="section-title2 text-center">...

HTML5, geolocation in real time with marker

I have this code: function startTracking() { var trackId = navigator.geolocation.watchPosition(successCallback, null, {maximumAge:1000, timeout:60000, enableHighAccuracy:true}); function successCallback(position){ map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude)); var marker = new google.maps.Marker({ position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude), map: map, title: 'Posizione Attuale' }); marker.setMap(map); }; } Now the app create a marker every time that I move. I...

how can I use 'localStorage' to store an entire page?

I've been reading the book HTML in action and in chapter 5 it shows how to create a mobile application that can be runned even offline. My only doubt is: Can I do it for an entire page? and can you give me a simple but complete example on how...

Equivalent of canvas quadraticCurveTo in SVG

I am working on a plugin to allow "natural looking" signatures to be drawn using mouse or touch. When confirmed by the user, the result will be a stored SVG that can then be displayed in place of the "Click to sign" button. The attached JSFiddle shows a testbed...

What is the semantic HTML tag to display for URLs that are not links?

I have a search engine plugin that outputs results in a basic structure: <a href="page url"> <div class="searchResult"> <h3>Page title</h3> <p>Page url</p> <p>Page <meta> description</p> </div> </a> The plugin is designed to integrate into an existing website so it has no default styling. However, websites are supposed to be usable...

More modern image maps?

With all the recent advances in JavaScript/HTML5 it would be nice to think there would be a more modern way of implementing an image map. I know you can set a map property for the tag but I don't think this supports nicely formatted tooltips on rollover (near the region)....

Custom Element extend from input type range

I can't figure out how to retrieve the current attr. value of the input type range element. The attr. value seems not be the 'internal attr. value' which is changed during slides. Javascript 'use-strict'; (function(){ var fooProt = Object.create(HTMLElement.prototype); Object.defineProperty(fooProt, "bar", { value: {test: 1}, writable: false, enumerable: true });...

why i don't get return value javascript

When i debug my code i can see i have value but i don't get value to createCheckBoxPlatform FN function createCheckBoxPlatform(data) { var platform = ""; $.each(data, function (i, item) { platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>' +...

Using destination-over to save background and actual sketch

I've read this and a few other questions, and it is clear I need to use destination-over to save the background and the sketch by display the new image over the old one. I'm using Sketch.JS with my code as such: var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); $('#myCanvas').sketch({...

jQuery & CSS only load after many refreshes

If you open this page in IE11, the CSS and jQuery don't load: If you refresh the page once, maybe even twice, it still doesn't load. But if you hit F5 a bunch of times in succession, the CSS and jQuery finally load and the page displays correctly. This...

Aligning StackPanel to top-center in Canvas

I'm trying to create an application which is supposed to measure quick reaction performance of it's user. The application starts up in full-screen mode and resizes it's elements accordingly to the screen resolution. The project was strongly inspired by training_aim_csgo2 map. It's mostly done, but here is the problem: I...

fabric.js resize canvas to fit screen

I'm currently developping an application on mobile device (android and iPhone) with ionic and cordova. I would like to edit a picture. I use fabric.js library to do that. Fabric.js converts an image and other items into canvas. Then I add some image on the canvas (stickers) and export it...

Saving image to localstorage - canvas

I'm using html5 storage to store my image. It works great in chrome. In FireFox it works 8/10 times. function getBase64Image(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); console.log("line 1 : " + img.src); var dataURL = canvas.toDataURL('image/jpeg'); console.log("line...

Redraw text over clearRect HTML5 Canvas

I'm trying to draw text (HTML5 canvas) depending on what option is selected in a select element. It works correctly until there's 2 set of text that appears at the same place. It seems like the clearRect function is the issue. The text won't be redrawn over that cleared space....

Spring Mobile apps to be deployed in emulator

I'm trying to develop an application based on Spring MVC for mobile device. Spring Mobile do provide such features to view our application in mobile browser. But how can I run/deploy the application in emulator since it's non-android based application? Also if can anybody tell me, how can I test...

Teechart HTML5, line color and thickness

How do you change the line color and thickness of a series in Teechart HTML5. I have been looking through the examples, but i can't find anything describing that....

Prevent bootstrap 3 tab from stacking when window is resized (made smaller)

I have two tabs and I do not want them to stack when the window is resized. How do I do so? As shown below this is the code I've used to create my tabs. I don't understand why they would stack up when my window is resized. HTML Tab...

boostrap & Normalize.css: spacing problems

Boostrap normalize does not seem to remove top and left/right spacing from theme i am developing. Could somebody give hint where is the problem in my code. I have tried several reset css files also without any effects. Index <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- GOOGLE FONTS -->...

How secure are HTML5 forms?

<input id="user_lic" type="number" min="5" max="30" step="5" value ="5"/> Would someone be able to disable this min="5" statement and then submit the input with a negative value. Or for example bypass the type=number statement and enter a symbol...

Unwanted Space Between

I have the following HTML5 code: <!doctype html> <html> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <style> body { max-width: 960px; margin: 0 auto; font-size: 120%; } header, nav { margin: 0; padding: 0; border: 1px solid black; } header { border-color: red; } img.mainpicture { width: 100%; height: auto;...

Tagging values in HTML document for automated extraction

We have a series of documents that are being converted to HTML for web access. The documents are operating instructions that list actions people have to do as well as distinct requirements. We wanted to put a tag around each requirement so it can be automatically extracted using some code....

Swap nav and div vertically uing CSS only

So I have a <nav> in my <header> tag and just below it I have a <div> which shows the date. Now the problem is, my design is in such a way that I cannot put the <div> for the date inside my <header>. However since I'm working with a...

Does localStorage.clear(); clear ALL from PC?

If I call the following: window.onbeforeunload = function() { localStorage.clear(); }; Does this clear all local storage from a user machine or just what my site has set?...

How can you drop an image from your desktop into an editor and move it around?

The default behavior when you drop something from your desktop to a textarea is that you will see the path to the image at the position where you dropped it. My end goal is to convert the local image as base64 and insert it at the drop position within the...

Canvas element does not resize when using ReactJS and PaperJS together

I have found that canvas elements correctly resize on window resize when they are inside react components. They also resize correctly when used with PaperJS. However, they do not resize when used with PaperJS and ReactJS together. Is this an incompatibility between PaperJS and ReactJS or am I instantiating PaperJS...

JSON.parse parsing a string into string

I have confusion over the functionality of JSON.parse. I am writing code : dynamicMsgObj = '"rest, no disc"'; var jsonObj = {}; var isJsonString = function isJsonString(str) { try { jsonObj = JSON.parse(str); } catch (e) { return false; } return true; }(dynamicMsgObj); console.log(isJsonString);// returns true console.log(typeof jsonObj);//returns string How...

How to make my nav bar responsive

I would like to use media query to make my navbar responsive. @media screen and (max-width: 600px) { .nav-wrap { position: relative; min-height: 40px; } .nav-wrap ul { position: absolute; } .nav-wrap li { display: none; /* hide all <li> items */ margin: 0; } .nav-wrap .current_page_item { display: block;...

Using Aria to make a div table accessible

Context: I have a div table that a client wants to be screen reader accessible like a regular html table is using the table commands Problem: Cant get aria to work to announce the header with the row value to keep the integrity intact with the data. Solutions: Only using...

How to move a canvas element up and down for a certain amount of time with javascript

I'm trying to make 6 guitars strings move when they are clicked on. I tried doing a simple animation by moving the string 2.5 px up and 2.5 px down for 3 seconds. but I don't really know how to do that. This is what I've tried: function onLoad(){ snaren();...

How to make a Javafx Image Crop App

I am building an application for my colleagues to crop image. I use FXML with Scene Builder to build the GUI. The user click a button to choose a image from his computer. Then, the image is shown in the GUI. User can zoom and move in the pane. At...

How to change my table based on screen size?

I want to change my table so it would look nice on a mobile platform. All I want to do is change my table so it is two columns. I am using this code to send an email. So I cannot link a stylesheet to my html. It is recommended...

Animate dots or points from an offset to their actual position

How can I do the animation by using SVG or CSS? Animation should be like below: Initially, only lines will be visible(picture 1), after 2 seconds dots (.) will come and join to the line curves(picture 2) with some animation to the dots. Online Example Please check the code below...

How can I make a DIV element Fixed but non-Scaleable?

Hopefully I'm asking this question right. Basically, I'm trying to implement a drop down menu into my design. I've been looking around for help coding it, since I'm still relatively new to HTML/CSS and found a few great tutorials that I have altered a bit to match what I have...

how to add a message (memo / sticky note) on (top of existing) html page

How do I achieve this: I have an HTML5 homepage and want to give the visitors a message (e.g. "dear visitor, I am on vacation from....") in the form of a memo/sticky note e.g. in the top right corner of the home page. Is there a neat and nice solution...

How to read all video type in a video tag

I make a web interface for my server and I want to read all my video, but I have some problems: When I change the innerHTML (in javascript) of my video tag with a new source tag, it keep playing the previous video then I need to refresh the page...

html query string with blackberry

My hybrid mobile app needs to work on blackberry devices as well. I noticed that a simple html query string such as Works also this way using the anchor tag (even if it is not standard) using Android and iOS. I don't have a blackberry to try but...

javascript onblur onMouseOver calculate tax and autofill form input

After 2 days searching I give up. I have a form and need to add (autofill) taxes to the input total price but in a easy simple way: <form name="form" action="go.php"> <input name="cost" type="text"> <input name="costplustax" type="text" value=" here we autofill cost +19%> <input type="submit" value="ready to mysql"> I can...

Canvas borders c# ( Windows Phone 7)

I am using Storyboard to move my Images in Canvas. I am wondering if there is an option, when Image is moving to bottom and get into bottom border and Image will not move more down but also not stay. The point is how to make that Image will just...

Sending input data to a javascript file

My following code is this: <form> <input class="inputField" type="text" required="required" pattern="[a-zA-Z]+" /> <input class="myButton" type="submit" value="Submit" /> </form> <script type="text/javascript"> $(document).ready(function () { $(".myButton").on("click", function () { var value = $(".inputField").val(); }); }); </script> I want to send to the file main.js the data after a user puts in some...

Load javascript in consecutive order after browser load event

What am I trying to do? In an attempt to speed up my website I am loading non-essential javascript after the browser load event. (So the JS files are not render blocking) This is currently functioning correctly. What is the problem? The problem is sometimes the non-essential javascript depends on...

validation of AngularJS direcrives

I read on W3C School that to make a valid HTML page I have to add data before each angular directive in HTML file (e.g.: <p>The name is <span data-ng-bind="firstName"></span></p> or <div data-ng-app="" data-ng-init="firstName='John'"> Ok that's fine. I have two questions: Should this prefix be used only for ng- directives?...

HTML - How to properly mark a phrase

The <blockquote> tag demand a cite external source, but what if the only source is the name of the phrase author? The <cite> tag defines the name of a work (e.g. a book, a song, a movie, a TV show, a painting, a sculpture, etc.), so it's no suitable to...

Retrive geolocation in real time (HTML5)

I have this code: var map; var geocoder; function initialize() { var mapOptions = { zoom: 18 }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); // Try HTML5 geolocation if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); var marker = new google.maps.Marker({ position: pos, map: map, title: 'Posizione Attuale' });...

onended audio event firing without playing the audio

I have multiple audio files that i need to be played. and only when all audio has been played completely the next section is supposed to show. the code that i've written fires automatically without playing any audio. how should i do it? here's my code <!DOCTYPE html> <html> <body>...

change icon on collapse in Bootstrap 2.3 not in bootstrap 3

I am using bootstrap 2.3 collapse in my project. I need to change icons on collapse means on show and hide I need to change icons. with bootstrap 3 some shown and hidden functions are showing in internet but I need with Bootstrap 2.3. Please let me know how to...

Common CSS in all HTML Files [on hold]

Can I include all my css in my header.html and include that common header.html in all my files or i need to give reference to the same css in all my html files? I know i can include all my JS files in a common header.html because you can put...